登录
首页 >  Golang >  Go问答

Go中使用Matlab DLL代替Python

来源:stackoverflow

时间:2024-02-15 16:45:22 106浏览 收藏

大家好,今天本人给大家带来文章《Go中使用Matlab DLL代替Python》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我使用的是 matlab simulink/codegen 生成的 dll 模型。

代码在 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

我只是想将上面的代码翻译成go以提高性能。问题在于 syscall.syscall 无法识别 real_t (c.double) 类型以返回双精度值而不是指针。

如何在 go 中设置 "my_custom_input" 值并读取 "my_custom_output" 值?


正确答案


刚刚找到了一个使用 lazydll 的新解决方案。 完整代码为:

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
}

好了,本文到此结束,带大家了解了《Go中使用Matlab DLL代替Python》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>