Looking for some pointers (no pun intended...) as to the best approach for this scenario.
So, I have a DLL (Provided Externally) that has the following exported function:
typedef std::function<void (
unsigned int msgType,
unsigned int size,
const char* const value
) > SCallback;
__declspec(dllexport) int StartS( SCallback fnS );
I'm attempting to call this from a C# Console Application, and this is what I am doing:
[DllImport("SeqLib.dll", EntryPoint = "?StartS@SApi@@YAKV?$function@$$A6AXIIPBD@Z@std@@@Z", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public static extern int StartS(DCallback cb);
public delegate void DCallback(int msgType, int size, IntPtr value);
public static void MessageReceived(int msgType, int size, IntPtr value)
{
return 0;
}
DCallback callback = new DCallback(MessageReceived);
StartS(callback);
Running this gives:
System.AccessViolationException: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Exception aside, is there something wrong with the basic approach above? Can anyone advise on the correct approach to calling an exported function that has a std::function parameter as above?
Thanks in advance.
extern "C"to prevent name mangling. @PepijnKramer That is really not correct, it's perfectly possible to use C++ functions, you just need to prevent mangling and not use C++ objects (as C++ can't interact or destroy them)