Changing a C# delegate's calling convention to CDECL

Armen Tsirunyan picture Armen Tsirunyan · Mar 1, 2011 · Viewed 10.7k times · Source

I have had this problem with C# when I was using DotNet1.1

The problem is this. I have an unmanaged dll, which has a function which takes a function pointer (among other arguments). When I declare the DLLImport in C# code, I pass a delegate. But the delegates in C# have stdcall calling convention whereas the unmanaged function expects a cdecl function pointer. Thus my naive approach resulted in crashes. Then I found the following: http://www.codeproject.com/KB/cs/cdeclcallback.aspx Some guy wrote an excellent library that enables changing calling convention of the delegate by, as I understood, MSIL-hacking. Things went well, until...

I migrated to VS2008 and the new version of .NET. Under this version the abovementioned library doesn't work. I am not really a C# or .NET expert, and, to tell the truth, I barely understand what his library does (although it's open-source), so I don't even want to try to adapt it to new .NET. However I am hoping that newer version of C# has some better solution available for my problem.

So, SO experts, please help me with my pain in the buttocks :)

Answer

David Heffernan picture David Heffernan · Mar 1, 2011

By default the p/invoke system wraps your delegate in a stdcall function. You can change the generated wrapper's calling convention by using the UnmanagedFunctionPointer attribute:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MyDelegate();