1.8 KiB
| tags |
|---|
| dev |
Multi Language Library
To create a library that can be used in multiple languages, the language that is going to implement the library needs to support notes/ffi with the language that the library is written in.
With this in, we can use the following in our favor:
- It's impossible that every language support every other language.
- For compatibility reasons, Almost every language supports C's notes/abi for their notes/ffi.
- Some compiled language has the avility to compile a C's "dynamic library" (
.sofile in unix and.dllin windows). - The notes/ffi use a "dynamic library" to work.
So, in conclusion: we can use whatever language that supports compiling to C's ABI to build multi language libraries
List of language that compiles to C's ABI
Go
To produce a shared library, you need to compile it with compile with: go build -buildmode=c-shared.
Note that the documentation says you need to specify with functions needs to be exported:
Build the listed main package, plus all packages it imports, into a C shared library. The only callable symbols will be those functions exported using a cgo //export comment. Requires exactly one main package to be listed.
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
Sources:
- https://stackoverflow.com/questions/75035609/can-go-executable-be-used-as-a-dynamic-library
- https://pkg.go.dev/cmd/go#hdr-Build_modes