提问人:Marcello 提问时间:11/17/2023 更新时间:11/17/2023 访问量:37
如何在 C 语言中定义函数并在 Go 代码中调用回调?
how can i define function in c and invoked callback in go code?
问:
我需要使用去生成.dll文件 .dll 定义了回调函数,如下所示:
main.go(主去)
//export HandleDatagramCallback
func HandleDatagramCallback(f func(int32)) {
// the f is c callback
// maby the f is void* in c, like go unsafe.point()
// but i dont known how unsafe.point convert to go function ?
f(1)
}
去构建生成 .dll
go build -buildmode=c-shared -o webtransport.dll main.go
C代码:
typedef void(__stdcall* f_funci)(void*);
void __stdcall NewCallback(int size) { // The function is called correctly
cout << "callback: " << endl;
cout << "size:" << size << endl; // here, the int size it's random mem ptr ??? it problem
}
int main() {
HINSTANCE dll = LoadLibrary("webtransport.dll");
if (!dll) {
cout << "load dll failed!" << endl;
return 0;
}
//
f_funci callback = (f_funci)GetProcAddress(dll, ("HandleDatagramCallback") );
if (!callback) {
out << "could not locate the function HandleDatagramCallback" << endl;
return 0;
}
void* c = NewCallback;
// tell golang callback function ptr
callback(&cb);
}
当我运行C代码时,回调函数成功, 但是无法收到任何参数,请帮忙,谢谢
给出一个 C 回调,golang 调用回调,C 正确接收参数 我尝试使用C struct,它失败了;喜欢:
GO代码:
//export HandleDatagramCallback
func HandleDatagramCallback(f unsafe.Pointer) {
var ccx = *(*Callback)(f)
ccx.CallbackFn(123)
}
C代码:
typedef void(*CallbackFn)(int i);
typedef struct {
CallbackFn callbackfn;
} Callbacks;
... some same code
Callbacks cb;
cb.callbackfn = NewCallback;
callback((void*)(&cb));
使用这个想法,我认为 C void* 像 Go Unsafe.pointer 和 C 结构像 Go 接口。
请帮忙,非常感谢
答: 暂无答案
评论