Set a pointer to a C ++ function as a C # delegate

I have an unmanaged C ++ application as a COM client and C # COM server. now I want the COM server to be able to call the C ++ function.

WITH#:

[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 if this is the right way to just pass the pointer of the OnCallBack function to SetCallBack. I noticed that some examples of calling GetDelegateForFunctionPointer must GetProcessAddress in order to get the address of a function pointer, but I cannot do this, because there may be different C ++ COM clients with a different function name.

any suggestion?

+4
source share
1 answer

One way to do this is to show your C ++ functions using __declspec(dllexport) , and then just write P / Invoke for these functions. Now you can use these P / Invoke functions as delegates.

In depth, this is essentially a GetProcAddress approach, but the C # compiler makes it syntactically more enjoyable for you.

0
source

All Articles