Calling a DLL function containing a function pointer from C #

I have a C ++ dll that includes an exported function that has pointers to functions to be used as a callback function.

// C++ DllExport unsigned int DllFunctionPointer( unsigned int i, unsigned int (*TimesThree)( unsigned int number ) ) { return TimesThree( i ) ; } 

I have a CSharp application that I would like to use to call DLL functions.

 // C# public unsafe delegate System.UInt32 CallBack( System.UInt32 number ); class Program { [DllImport("SimpleDLL.dll")] public static extern System.UInt32 DllFunctionPointer( System.UInt32 i, CallBack cb) ; static unsafe void Main(string[] args) { System.UInt32 j = 3; System.UInt32 jRet = DllFunctionPointer(j, CallBack ); System.Console.WriteLine("j={0}, jRet={1}", j, jRet); } static System.UInt32 CallBack( System.UInt32 number ) { return number * 3 ; } } 

The problem with the code above is that the application crashes with the following error message.

 'CallingACallbackFromADLL.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\XXXX\CallingACallbackFromADLL.exe', Symbols loaded. Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\XXXX\CallingACallbackFromADLL.vshost.exe'. Additional Information: A call to PInvoke function 'CallingACallbackFromADLL!CallingACallbackFromADLL.Program::DllFunction' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. The program '[9136] CallingACallbackFromADLL.vshost.exe: Managed (v4.0.30319)' has exited with code 1073741855 (0x4000001f). 

I'm not sure what to do next.

My question is:

  • What is the correct way to call a C ++ DLL function containing a callback pointer from a C # application.
+4
source share
1 answer

This is because by default the call to conditional functions in C# is __stdcall , but in C/C++ , __cdecl used by __cdecl , so you should change the convention of calling your function as follows:

 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void TimesTree( uint frame ); [DllImport("SimpleDLL.dll")] public static extern System.UInt32 DllFunctionPointer( uint i, [MarshalAs(UnmanagedType.FunctionPtr)] TimesTree callback ) ; static unsafe void Main(string[] args) { // ... System.UInt32 jRet = DllFunctionPointer(j, CallBack ); // ... } 
+3
source

Source: https://habr.com/ru/post/1444694/


All Articles