Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

c++ - Changing a C# delegate's calling convention to CDECL

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...