Search code examples
c#c++callbackcom-interop

set C++ function pointer as C# delegate


I have a unmanaged c++ application as COM client and a C# COM server. now i want COM server can invoke a c++ function.

C# :

[ClassInterface(ClassInterfaceType.AutoDual)]
public class SomeType
{
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void DeleCallBack(string info);
    public DeleCallBack CallBack;
    public void  SetCallBack(ref IntPtr ptr)
    {
        CallBack = (DeleCallBack)Marshal.GetDelegateForFunctionPointer(ptr, typeof(DeleCallBack));
    }
}

C++:

HRESULT hr = E_FAIL;
CComPtr<WindowsFormsApplicationVC9::_SomeType> spTmp;
hr = spTmp.CoCreateInstance(__uuidof(WindowsFormsApplicationVC9::SomeType));
if (SUCCEEDED(hr))
{
    spTmp->SetCallBack(OnCallBack);
}
void  OnCallBack(BSTR info)
{
    // c++ function call...;
}

I'm not sure it is the right way to just pass the OnCallBack function pointer to SetCallBack. I noticed that some sample of calling GetDelegateForFunctionPointer should GetProcessAddress to get the function pointer address, but i can't do that since there are may be different c++ COM client with different function name.

any suggestion?


Solution

  • One way to do it is to expose your C++ functions via __declspec(dllexport), then simply write P/Invoke for those functions. Now you can use those P/Invoke functions as delegates.

    Deep down this is essentially the GetProcAddress approach but the C# compiler makes it syntactically nicer for you.