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 關注
- 111 瀏覽
添加回答
舉報