PInvoke DLL in C#

前端 未结 2 927
有刺的猬
有刺的猬 2021-01-03 14:51

I want to pass a structure to C function and I write the following code.

When I run it, the first function - Foo1 is working and then function Foo

2条回答
  •  心在旅途
    2021-01-03 15:12

    You are using C call so you need to specify CallingConvention.Cdecl

    [DllImport(@"C:\.net course\unmanaged1\unmanaged3\Debug\unmanaged3.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
    

    By default its stdcall in C# pinvoke as i remember; You can also do change C code instead and leave your C# code as is like in below

    __declspec(dllexport) void __stdcall  Foo(void  *Test);
    

    But for me best is to both declare __cdecl (or stdcall) in your C export and CallingConvention.Cdecl (or stdcall) in your C# code to keep convenience. You can check https://docs.microsoft.com/en-gb/cpp/cpp/argument-passing-and-naming-conventions?view=vs-2017 and https://docs.microsoft.com/en-gb/dotnet/api/system.runtime.interopservices.callingconvention?view=netframework-4.7.2 for further info

提交回复
热议问题