how can i define function in c and invoked callback in go code?

62 views Asked by At

I need use go generate .dll file the .dll defined the callback function like:

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)
}

go build generate .dll

go build -buildmode=c-shared -o webtransport.dll main.go

C code:

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);
}

when i run c code, callback the function successed, but can not receive any parameter, please help, thank you

give go a C callback, golang invoke the callback, C receive parameters correctly i'm try use c struct, it's failed; like:

go code:

//export HandleDatagramCallback
func HandleDatagramCallback(f unsafe.Pointer) {
    var ccx = *(*Callback)(f)
    ccx.CallbackFn(123)
}

c code:

typedef void(*CallbackFn)(int i);
typedef struct {
    CallbackFn callbackfn;
} Callbacks;

... some same code

Callbacks cb;
cb.callbackfn = NewCallback;
callback((void*)(&cb));

use this idea, i think think the c void* like go unsafe.pointer and the c struct like go interface.

please help, thank very much

0

There are 0 answers