英文:
Dynamic FFI in Go
问题
在Go语言中,是否可以动态地加载外部的C库(dll)并调用其函数?
我知道有cgo
可以用来静态地绑定C函数,但我对动态方式更感兴趣。
英文:
Is it possible to dynamically load foreign C library (dll) and call its functions in Go?
I know there is cgo
which is used to statically bind to C functions, but I'm interested in dynamic way.
答案1
得分: 7
简短回答:不行(至少使用gc编译器不行,但gccgo是可以与gcc链接的,所以可能是可行的)。
中等回答:但是,你可以静态绑定libffi或libdl,然后使用它来动态加载其他库。
长回答:你可以使用go工具链的C编译器和汇编器(参见src/pkg/runtime)编写C和ASM的go包。因此,你可以将C或ASM作为go包编写FFI。
编辑:根据下面的评论(现在也是CW)
另外,可以使用syscall和unsafe包来实现(在Windows上很容易,但我想在Linux上可能会更困难,与上面的第三种解决方案差不多)。
http://code.google.com/p/go/wiki/CallingWindowsDLLs
英文:
Short answer: no. (at least not with gc, gccgo is gcc linkable however, so it might be possible)
Medium answer: However, you can statically bind, say, libffi or libdl and then use it to dynamically load other libraries.
Long answer: You can write go packages in C and ASM using the go toolchains C compiler and assembler (see src/pkg/runtime for example). So you could write a FFI in either C or ASM as a go package.
Edit: From the comments below (also CW now)
Alternatively, it can be done using the <code>syscall</code> and <code>unsafe</code> packages (easily in windows, but I imagine it would be harder in linux and not far off from the third solution above).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论