调用DLL方法时,方法的类型签名与PInvoke不兼容

ska*_*red 2 c c# c++ dll dllimport

我有一个带有接口的DLL

struct modeegPackage
{
    uint8_t     version;    // = 2
    uint8_t     count;      // packet counter. Increases by 1 each packet
    uint16_t    data[6];    // 10-bit sample (= 0 - 1023) in big endian (Motorola) format
    uint8_t     switches;   // State of PD5 to PD2, in bits 3 to 0
};

__declspec(dllexport) void __cdecl initSerial();

__declspec(dllexport) void __cdecl closeSerialPort();

__declspec(dllexport) struct modeegPackage __cdecl getPackage();
Run Code Online (Sandbox Code Playgroud)

和C#适配器

class EEGCommunication
{
    [StructLayout(LayoutKind.Sequential)]
    public struct modeegPackage
    {

        /// unsigned char
        public byte version;

        /// unsigned char
        public byte count;

        /// unsigned int[6]
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.U2)]
        public UInt16[] data;

        /// unsigned char
        public byte switches;
    }

    private const string DLL = "libneureader-lib.dll";

    [DllImport(DLL, EntryPoint = "_Z10initSerialv")]
    public static extern void InitSerial();

    [DllImport(DLL, EntryPoint = "_Z15closeSerialPortv")]
    internal static extern void CloseSerialPort();

    [DllImport(DLL, EntryPoint = "_Z10getPackagev", CallingConvention = CallingConvention.Cdecl)]
    public static extern modeegPackage GetPackage();
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试调用GetPackage方法时,我收到一个错误Method's type signature is not PInvoke compatible.

我的代码有什么问题?

更新:代码已更新

xIn*_*rop 5

在我的面前被标记为“ ANSWER”的答案并不是真的正确,并且已经存在了1.5年。

OP出现该错误的原因确实就是错误描述所言,“方法的类型签名与PInvoke不兼容”

当您拥有C / C ++函数(例如下面声明的函数)时,

    __declspec(dllexport) struct modeegPackage __cdecl getPackage();
Run Code Online (Sandbox Code Playgroud)

由于该函数返回的struct值大于任何寄存器可以容纳的值,因此GCC编译器将尝试对其进行优化(Return Value Optimize),因此实际实现如下所示:

    __declspec(dllexport) void __cdecl getPackage(struct* modeegPackage);
Run Code Online (Sandbox Code Playgroud)

因此,您的P / Invoke声明应为

    [DllImport(DLL, EntryPoint = "_Z10getPackagev", CallingConvention = CallingConvention.Cdecl)]
    public static extern GetPackage(out modeegPackage);
Run Code Online (Sandbox Code Playgroud)

希望我的回答对以后可能遇到类似问题的其他开发人员有所帮助。