I recently worked on the interaction of C # with C ++, in particular, setting up a callback function that is called from the C ++ DLL.
namespace TomCSharpDLLImport { class Program { public delegate void TomDelegate(int a, int b); [DllImport("TomDllNative.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void GetData(); [DllImport("TomDllNative.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void SetCallback(TomDelegate aCallback); static void Main(string[] args) { TomDelegate lTD = new TomDelegate(Program.TomCallback); SetCallback(lTD);
The question is, when a program control enters the TomCallback function, I expected it to hit the while (true) loop in Main. However, instead, the program simply exits. I canβt help but discern my behavior, part of me imagines that this is as expected, but part of me expected that this will continue mainly.
What did I expect ...
- The GetData () function is called
- GetData function calls a callback
- The callback function returns to GetData li>
- GetData returns to main ()
However, this is not entirely correct.
Someone will be kind enough to explain what is happening.
To save space, I did not send unmanaged code, however, if necessary, I am happy to publish
Edit: I turned on unmanaged debugging (completely forgot to do this), and now I see a crash.
Runtime Check Error # 0 - ESP value was not properly stored during function call. This is usually the result of calling a function declared with one call, with a function pointer declared with another calling convention.
Source code since this is a crash
#include "stdafx.h" typedef void (*callback_function)(int, int); extern "C" __declspec(dllexport) void SetCallback(callback_function aCallback); extern "C" __declspec(dllexport) void GetData(); callback_function gCBF; __declspec(dllexport) void SetCallback(callback_function aCallback) { gCBF = aCallback; } __declspec(dllexport) void GetData() { gCBF(1, 2); }