1 回答

TA贡献1816条经验 获得超4个赞
这里有几个问题。首先是类型的不兼容。Go 将返回一个 GoInt。第二个问题是Add()必须导出该函数才能获取所需的头文件。如果您不想更改 Go 代码,那么在 C 中您必须GoInt使用long long.
一个完整的例子是:
测试.go
package main
import "C"
//export Add
func Add() C.int {
var a = 23
return C.int(a)
}
func main() {}
测试.c
#include "test.h"
#include <stdio.h>
int main() {
int number = Add();
printf("%d\n", number);
}
然后编译并运行:
go build -o test.so -buildmode=c-shared test.go
gcc -o test test.c ./test.so &&
./test
23
GoInt使用: test.go 的第二个示例
package main
import "C"
//export Add
func Add() int { // returns a GoInt (typedef long long GoInt)
var a = 23
return a
}
func main() {}
测试.c
#include "test.h"
#include <stdio.h>
int main() {
long long number = Add();
printf("%lld\n", number);
}
然后编译并运行:
go build -o test.so -buildmode=c-shared test.go
gcc -o test test.c ./test.so &&
./test
23
- 1 回答
- 0 关注
- 130 浏览
添加回答
举报