首页 > 解决方案 > 将 GO 指针传递给 C 回调函数

问题描述

我需要将函数指针作为参数(即回调函数)传递给共享对象内的 C 函数。期望是从共享对象内部的函数中获取回调。我需要在 GO 中实现该函数,并且应该作为 C 共享对象的回调调用。我的解决方案是在最后一步抛出分段错误。

//////////////in libcshared.so ///////////
typedef void (*test_function_ptr)(int a)
void callerfun(test_function_ptr callback)

//////////////in GO program//////C program
void* gofunptr;
void implfun(int x){
GOSharedfn(gofunptr);
}
-------------
func main(){
C.gofunptr = &gofun
var callback = C.test_function_ptr(unsafe.Pointer(C.implfun))
C.callerfun(callback )
}
var gofun = goimpl
func goimpl(){
}
/////////GO shared lib libgoshared.so/////////<br>
func GOSharedfn(unsafe.Pointer pointer){
f:=(cast to fun ptr)pointer
f();//Segmentation fault
}

函数调用流程图

标签: pointersgocgo

解决方案


推荐阅读