Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use cdecl callback with pinvoke

I have a c library that has cdecl callbacks. How can I use these from c#.

Everything seems to say that they must be stdcall callbacks

to be clear:

delegate int del();
[dllimport("mylib.dll",CallingConvention=CallingConvention.Cdecl)]
public static extern int funcwithcallback(del foo);

where del must be called cdecl-wise

like image 880
pm100 Avatar asked Feb 03 '23 21:02

pm100


1 Answers

Take a look at this. The functionality has been around since 1.1 so it should cover whatever .NET version you are using. You just have to specify the CallingConvention.

CallingConvention Documenation at MSDN

You can also look at this article on Code Project:

Using the _CDECL calling convention in C#

EDIT: Also, Here is a example from FreeImage.NET.

static FreeImage_OutputMessageFunction freeimage_outputmessage_proc = NULL;
DLL_API void DLL_CALLCONV
FreeImage_SetOutputMessage(FreeImage_OutputMessageFunction omf);

Then on the C# side, simply:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FreeImage_OutputMessageFunction(FREE_IMAGE_FORMAT
format, string msg);

[DllImport(dllName, EntryPoint="FreeImage_SetOutputMessage")]
public static extern void SetOutputMessage(FreeImage_OutputMessageFunction
omf);
like image 149
Matt Avatar answered Feb 06 '23 14:02

Matt