英文:
Can Go executable be used as a dynamic library?
问题
我正在使用GoLang编写一个通用库,并希望将其发布为动态库,以供使用任何语言编写的其他应用程序使用。
如果我使用C/C++编写这个库,我会生成一个.dll或.so文件,可以在任何其他语言中导入和使用。在GoLang中,我该如何做到这一点?
如果我只生成一个Go可执行文件,能否将其用作动态库的替代品?
英文:
I am writing a generic library in GoLang and want to publish it (like a dynamic library) to be used by other apps written in any language.
If I write this lib in C/C++, I would have generated a .dll or .so file which can be imported and used in any other language. How can I do this in GoLang?
If I just generate a Go executable, can I use it instead of a dynamic library?
答案1
得分: 3
你可以在Go语言中构建一个C共享库,这将生成一个常规的.dll
或.so
文件,其中包含与C调用约定兼容的导出函数,以便可以从其他语言中调用它们。
使用go build -buildmode=c-shared
进行编译。
参见go build
命令 - 构建模式
例如:
src/go/main.go
:
package main
import "C"
import "fmt"
//export helloLib
func helloLib(x C.int) {
fmt.Printf("Hello from Go! x=%d\n", x)
}
func main() {}
src/c/main.c
:
void helloLib(int);
int main() {
helloLib(12345);
}
构建和运行:
$ go build -buildmode=c-shared -o libmy.so ./src/go/
$ gcc -o test src/c/main.c libmy.so
$ ./test
Hello from Go! x=12345
$
英文:
You can build a C-shared library in Go, this will produce a regular .dll
or .so
with exported functions compatible with the C calling convention, so that they can be invoked from other languages.
Compile with go build -buildmode=c-shared
.
See go build
command - Build modes
For example:
src/go/main.go
:
package main
import "C"
import "fmt"
//export helloLib
func helloLib(x C.int) {
fmt.Printf("Hello from Go! x=%d\n", x)
}
func main() {}
src/c/main.c
:
void helloLib(int);
int main() {
helloLib(12345);
}
Building and running:
$ go build -buildmode=c-shared -o libmy.so ./src/go/
$ gcc -o test src/c/main.c libmy.so
$ ./test
Hello from Go! x=12345
$
答案2
得分: -2
我相信可以使用cgo实现这个功能:
https://pkg.go.dev/cmd/cgo
文档中说明了Go函数可以导出供C代码使用。
英文:
I believe it is possible using cgo:
https://pkg.go.dev/cmd/cgo
It is stated that Go functions can be exported for use by C code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论