Using a C-callback function with .NET

早过忘川 提交于 2019-12-11 17:52:49

问题


I'm using a C-library from within .NET This all works quite nice. But I'm having troubles with a callback function.

I have this C-code:

Bool someCallBack(const char *name, int reason)
{
    //some logic here
    return True;
}

int main(int argc, char **argv){
    SetCallback(someCallBack)
}

In the header file the SetCallback is defined as:

typedef Bool (*CallbackType)(const char *name, int reason); 
#define DLL_USE __declspec(dllimport)
DLL_USE void SetCallback(CallbackType callBack);

When I execute a function that triggers the call back, this all works fine in C.

Now I want to do this from within .NET

In .NET i have this code

<DllImport(CST.LIBRARY_NAME, entrypoint:="SetCallback")> _
Public Shared Sub SetCallback(ByVal callBack As CallbackType)
End Sub

Delegate Function CallbackType(ByVal name As StringBuilder, ByVal reason As Integer) As Boolean

Private Function TEST(ByVal name As StringBuilder, ByVal reason As Integer) As Boolean
    Debug.WriteLine("Hello Callback")
    Return True
End Function

SetCallback(New CallbackType(AddressOf TEST))

When I now execute the function that triggers a call back, The callback function is never triggered.

Is this the correct way to interop a Callback function?? Or what else could be wrong.

来源:https://stackoverflow.com/questions/9290980/using-a-c-callback-function-with-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!