开发者

callbacks inside a DLL?

I have a callback inside a C DLL (static void __stdcall) . I want another program to register it as such (by passing it the func ptr) and then call the calback inside the DLL. I have had no luck so far. However, the same callback works if its inside a regular C++ program. I am now wondering if having callbacks in a DLL is even possible. Any help will be appreciated!

Thanks.

Adding some code:开发者_开发知识库

C# app:

    [DllImport("DLLfilename.dll")]
    public static extern void DLL_SetCallback(CallbackDelegate pfn);

    public delegate void CallbackDelegate();

    //setDelegate() is called in init() of the C# app
    public void setDelegate()
    {
        CallbackDelegate CallbackDelegateInstance = new CallbackDelegate(callback);
        DLL_SetCallback(CallbackDelegateInstance);
    }

    public void callback()
    {
        //This is the function which will be called by the DLL

        MessageBox.Show("Called from the DLL..");
    }

C DLL: //is linked to externalLibrary.lib

    #include "externalLibrary.h"
    typedef void (__stdcall CallbackFunc)(void);
    CallbackFunc* func;    //global in DLL

    //Exported

    extern "C" __declspec(dllexport) void DLL_SetCallback(CallbackFunc* funcptr)
    {

      //setting the function pointer

        func = funcptr;
        return;
    }

//Exported

extern "C" __declspec(dllexport) void RegisterEventHandler(Target, Stream,&ProcessEvent , NULL)
{
     //ProcessEvent is func to be caled by 3rd party callback

     //Call third-party function to register &ProcessEvent func-ptr (succeeds)

     ...
     return;
}        

//This is the function which never gets called from the 3rd party callback
//But gets called when all the code in the DLL is moved to a standard C program.

void  __stdcall ProcessEvent (params..)
{
    //Do some work..

        func();         //Call the C# callback now


    return;
}


Your question is a little confusing. Are you saying that you have a non-exported function within a DLL, which you wish to take the address of and pass to some external code, which will call it back? That's perfectly reasonable to do. If it's not working, here are the things to look at.

1) Make sure that the calling convention is correct on the definition of the function, the type of the function pointer within your DLL, and the type of the function pointer as declared in the external code.

2) Within your DLL, attempt to call the callback through the same function pointer that you're passing to the external code.

3) If (1) is correct, and (2) works, then fire up your debugger, put a breakpoint on the line where you're trying to call the callback from external code, and then drop into disassembly. Step through the call and see where it ends up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜