C# DllImport with C++ boolean function not returning correctly

后端 未结 7 845
长发绾君心
长发绾君心 2020-11-29 04:20

I have the following function in a C++ DLL

extern \"C\" __declspec(dllexport) bool Exist(const char* name)
{
 //if (g_Queues.find(name) != g_Queues.end())
 /         


        
7条回答
  •  余生分开走
    2020-11-29 05:13

    I found the solution for your problem. Your declaration should be preceded with this marshaling: [return:MarshalAs(UnmanagedType.I1)]

    so everything should look like this:

    [DllImport("Whisper.dll", EntryPoint="Exist", CallingConvention=CallingConvention.Cdecl)]  
    [return:MarshalAs(UnmanagedType.I1)]  
    public static extern bool Exist([MarshalAs(UnmanagedType.LPStr)] string name);
    

    I tested it in my very simple example and it worked!

    EDIT
    Why this happens? C defines bool as 4 bytes int (as some of you have said) and C++ defines it as 1 byte. C# team decided to use 4 byte bool as default during PInvoke because most of the system API function use 4 bytes values as bool. If you want to change this behavior you have to do it with marshaling specifying that you want to use 1 byte value.

提交回复
热议问题