how to use cdecl callback with pinvoke

后端 未结 2 658
青春惊慌失措
青春惊慌失措 2021-02-08 21:12

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:



        
相关标签:
2条回答
  • 2021-02-08 21:58
    1. Compile with .NET 2.0, use 2005 compiler!!
    2. Reverse the argument direction.

    It works due to some safeguard code added by the 2005 compiler.

    EDIT: Don't try this if you can possibly make a shim in native code.

    0 讨论(0)
  • 2021-02-08 22:05

    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);
    
    0 讨论(0)
提交回复
热议问题