Search code examples
pythonmatlabgodllctypes

Using Matlab DLL in Go instead Python


I'm using a DLL model generated by Matlab Simulink/Codegen.

The code works pretty well in Python:

import ctypes
real_T = ctypes.c_double

# Importa a DLL
dll = ctypes.windll.LoadLibrary("./simulink.dll")

# Simulate
dll.initialize()     # Init
for i in range(10):
   mdlInput = (real_T).in_dll(dll, "my_custom_input")
   mdlInput.value = i
   # Step
   dll.step() # step
   # get output
   mdlOutput = (real_T).in_dll(dll, "my_custom_output")
   print(mdlOutput.value)
dll.terminate() # end of simulation

I just want to translate the code above to Go to increase performance. The problem is that syscall.syscall does not recognize the real_T (C.Double) type to return a double instead of a pointer.

How do I set the "my_custom_input" value and read the "my_custom_output" value in Go?


Solution

  • Just found a new solution using LazyDll. The complete code as:

    package main
    
    import (
        "log"
        "syscall"
        "unsafe"
    )
    
    func main() {
        dll = syscall.NewLazyDLL(".\\simulink.dll") // Load DLL as LazyDll
        dll.NewProc("initialize").Call() // Call initialize method from dll
        // Now get pointer to custom input
        customInput := (*float64)(unsafe.Pointer(dll.NewProc("my_custom_input").Addr()))
        // Update custom Input Value
        *customInput := 1.23
        // Call the step method from dll
        dll.NewProc("step").Call() // Call step method from dll
        // Now get pointer to custom output and show it's value
        customOutput := (*float64)(unsafe.Pointer(dll.NewProc("my_custom_output").Addr()))
        // Print the value of output
        log.Print(*customOutput)
        // Terminate the dll execution
        dll.NewProc("terminate").Call() // Call terminate method from dll
    }