而DLL调用方法方法的类型签名不兼容的PInvoke [英] Method's type signature is not PInvoke compatible while calling DLL method

查看:1157
本文介绍了而DLL调用方法方法的类型签名不兼容的PInvoke的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接口的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();

和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();
}

但是,当我试图调用 GetPackage 的方法,我收到一个错误方法的类型签名不是的PInvoke兼容。

But when I'm trying to call GetPackage method, I receive an error Method's type signature is not PInvoke compatible.

这有什么错我的code?

What's wrong with my code?

更新:code更新

推荐答案

这是导致问题的数组。该PInvoke的编组不喜欢用它作为一个函数的返回值按值返回结构的具体情况处理。它是在一般麻烦,这是做的方式是高度依赖编译器。有了你就会有麻烦,因为它听起来像你正在使用GCC好机会。它的一般的调用方分配堆栈上的返回值空间和一个指针传递给它做。

It is the array that is causing the problem. The pinvoke marshaller doesn't like dealing with it in the specific case of returning a structure by value as a function return value. It is in general troublesome, the way this is done is highly compiler dependent. With good odds that you'll have trouble since it sounds like you are using GCC. It is typically done by the caller allocating space for the return value on the stack and passing a pointer to it.

一个粗糙但是有效的一招是给自己扩大阵列,实用,够用,因为它只有6个元素。替换数组是这样的:

A crude but effective trick is to expand the array yourself, practical enough since it has only 6 elements. Substitute the array like this:

        /// unsigned int[6]
        public short data0;
        public short data1;
        //...
        public short data5;

这将解决该异常。无论你正确地获取数据还有待观察,如果没有,那么你可能要切换到MSVC。

Which will solve the exception. Whether you'll get the data correctly remains to be seen, if not then you may have to switch to MSVC.

这篇关于而DLL调用方法方法的类型签名不兼容的PInvoke的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆