Invoking an inline callback from .NET managed code (when loading managed code using COM)

I am really confused by a lot of misinformation about native / guided interaction.

I have a regular C ++ exe that is NOT built using CLR tools (this is not Managed C ++ nor C ++ / CLI, and never will be). This C ++ exe is "responsible", there is no managed wrapper for it.

I would like to access some of the code that I have in a C # assembly from my C ++ exe. I can access the C # assembly from my C ++ code using COM. However, when my C # code detects an event, I would like it to call back to my C ++ code. A C ++ function pointer for the callback will be provided at runtime. Note that a C ++ function pointer is a function found in the exe runtime. It can use static elements from there. I do not want managed code to try loading some DLL to call a function (no DLL).

How to pass this C ++ pointer to my C # code through COM / .NET and is its C # code successful?

Thanks!

+6
c # interop com com-interop
source share
2 answers

You might want to use Marshal.GetDelegateForFunctionPointer :

  • Create a delegate type that matches the signature of the native function, bearing in mind the correct way to sort the types and using MarshalAs as needed
  • Exchange the native function pointer with your own code to your C # code, however you can (in your case, it looks like you can use COM -> C # connection)
  • Use Marshal.GetDelegateForFunctionPointer to turn a pointer into a C # -callable delegate
  • Call a delegate with your options

Junfeng Zhang has an example of this here .

Pay attention to the restrictions specified in MSDN:

The GetDelegateForFunctionPointer method has the following limitations:

  • Generics are not supported in interop scripts.
  • You cannot pass an invalid function a pointer to this method.
  • You can use this method only for pure unmanaged function pointers.
  • You cannot use this method with function pointers obtained through C ++ or from the GetFunctionPointer method.
  • You cannot use this method to create a delegate from a function pointer to another managed delegate.

The C ++ part probably refers to function pointers for class methods. This should still work for global functions.

+6
source share

The standard COM approach is to subscribe to the event generated by the COM server. Usage can use the event keyword in C #, CLR interop automatically implements the necessary COM glue. Use the IConnectionPoint interface in your C ++ code. The backgrounder is here .

+4
source share

All Articles