英文:
How can I call linux shared library functions in Go?
问题
我有一个.so文件,我想在我的Go代码中调用其中的函数。
我该如何做?我已经阅读了cgo和syscall包。它们与我想要的接近,但我没有看到可以调用.so文件中函数的地方。
我想要实现的效果与Python中的ctypes包完全相同。
有人可以帮忙吗?
英文:
I have a .so file whose functions I would like to call in my Go code.
How do I go about doing that ? I have read the cgo and syscall package. They are close to what I want but I don't see any place where I can call the functions in the .so file.
I want to achieve exactly what the ctypes package does in Python.
Can somebody help ?
答案1
得分: 7
如果你想在编译时使用一个在编译时已知的共享库,你可以简单地使用cgo。阅读关于如何做到这一点的文档,但通常你需要指定一些链接器标志和一些被注释掉的行。下面是一个示例,演示如何从libfoo.so
调用函数bar()
。
package example
// #cgo LDFLAGS: -lfoo
//
// #include <foo.h>
import "C"
func main() {
C.bar()
}
你也可以使用cgo来访问在运行时动态加载的共享对象。你可以使用dlopen()
、dlsym()
和dlclose()
来打开一个共享库,检索其中一个函数的地址,最后关闭库。请注意,你不能在Go中完成这些操作,你需要编写一些在C中实现必要逻辑的包装代码。
英文:
If you want to use a shared library that is known statically at compile time, you can simply use cgo. Read the documentation on how to do that exactly, but usually you specify some linker flags and a couple of commented out lines. Here is an example on how to call function bar()
from libfoo.so
.
package example
// #cgo LDFLAGS: -lfoo
//
// #include <foo.h>
import "C"
func main() {
C.bar()
}
You can also use cgo to access shared objects that are being loaded dynamically at runtime. You can use dlopen()
, dlsym()
, and dlclose()
to open a shared library, retrieve the address of one of the functions inside and finally close the library. Notice that you can't do these things in Go, you have to write some wrapper code in C that implements the neccessary logic for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论