Reputation: 8462
I'm using from C# a C++ library that wasn't quite developed for using from another languages, but it's difficult to change something now. I'm using [DllImport] calls, and nearly everything works fine.
But know I need to use a "backward" call from C++ to C#. So, in C# I need to subscribe to the C++ function. In C++ it is implemented like this:
INTF_API void __stdcall Intf_InstallHandler(Intf_MailHdlPtrType Hdl)
typedef void (STDCALL *Intf_MailHdlPtrType)(InstanceNoType instno,
const MailType* mail, rsuint16 mailsize);
(I've removed a few arguments from the method to make it simplier. They are two bytes - not important) So in C# I have:
public delegate void MailEventHandler(byte Instance, MailType Mail, UInt16 MailLength);
MailHandlerDef defHandler = (f) =>
{
var structure =
(MailType)Marshal.PtrToStructure(f, typeof(MailType));
handler(structure);
};
Externs.Intf_InstallMailHandler(defHandler);
[DllImport(DLL_NAME, CallingConvention = CallingConvention.StdCall)]
public static extern void Intf_InstallMailHandler(byte Instance, [MarshalAs(UnmanagedType.FunctionPtr)] MailHandlerDef MailHandler, PrimitiveType Primitive);
We have different primitives (in C++ dll every method is a primitive, and every method is implemented as a call-and-wait method, or as an async method, where mailHandler is called on the end of the computation), and all primitives work, except one.
If this primitive is called, the NullRef exception is thrown, without any stacktrace. And I already lost my mind in trying to search what causing this. Intresting is that this doesn't work at our large application (even I tried to switch everyting off, and just call it at start up), but on my small test application it works.
Any help is appreciated.
Upvotes: 1
Views: 179
Reputation: 8830
you could use a .Net CLI C++ wrapper which would then call your standard C++ code.
Upvotes: 1