c - 如何调用作为参数接收的 C 函数
问题描述
我想使用在 C 中进行了一些调整的 Go 库。我制作了 GoAdder Go 函数,它有 3 个参数 int x、y 和函数类型为 f。
并且 GoAdder 函数将调用 f 参数。
加法器
package main
import "fmt"
import "C"
//export Ftest
type Ftest func(C.int);
//export GoAdder
func GoAdder(x, y int, f Ftest) int {
fmt.Printf("Go says: adding %v and %v\n", x, y)
f(10);
return x + y
}
func main() {} // Required but ignored
我在上面将 go 包构建为一个名为 libadder.a 的静态库,如下所示:
go build -buildmode=c-archive -o libadder.a adder.go
然后我在下面编写了 C++ 代码。
主程序
#include <stdio.h>
#include "adder/libadder.h"
void a( GoInt a ){
printf("Hello %d", a);
}
int main() {
printf("C says: about to call Go...\n");
int total = GoAdder(1, 7, &a);
printf("C says: Go calculated our total as %i\n", total);
return 0;
}
我已经像这样遵守了来源:
gcc -pthread -o static_go_lib main.c adder/libadder.a
执行上面的代码时会出现错误
unexpected fault address 0x0
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x80 addr=0x0 pc=0x563c99b74244]
goroutine 17 [running, locked to thread]:
...
如何在 go 函数GoAdder中获得正确的C 函数地址?
我引用了 https://github.com/draffensperger/go-interlang/tree/master/c_to_go/static_go_lib
解决方案
C函数只是跳转指针,而golang的回调是复杂的struct,不能转换。只有一种(安全)方法可以调用 C 函数指针:1)在某处声明:
//go:linkname cgocall runtime.cgocall
//go:nosplit
func cgocall(fn, arg unsafe.Pointer /* may be uintptr */) int32
2)另外,类型安全:
func GoAdder(x, y C.int, f unsafe.Pointer /* don't sure if this available, mb C.uintptr_t */) C.int
3) C 函数应该将指针(指向什么)作为参数
void a(GoInt *a)
(我会使用本机类型)
4)
ten := 10
cgocall(f, unsafe.Pointer(&ten))
(它应该是结构,如果你想传递几个参数)
推荐阅读
- node.js - 如何在 Node.js 的 VSCode 中运行带有附加环境变量 Debug=* 的脚本?
- excel - 查找 Excel 列、行
- angular - 将 Apollo Angular 2 用于 Angular ts-invariant/lib/invariant.d.ts:7:78 时出错
- function - SML/NJ:直接调用函数,而不是使用“val _ = fn....”
- javascript - 使用循环流式传输 html5 动画
- powershell - 按 csv 列分组对象并从另一列中选择最大值
- node.js - 如果 `accept-language` 标头中没有国家代码,何时询问客户他们的首选货币?
- javascript - 将 SQL 查询添加到 JSON 有效负载
- c++ - VS Code:C++ 中的文件系统问题
- c++ - 链接器如何找到正确的库?