日期:2014-05-17  浏览次数:20899 次

C#调用C++DLL
先有C++结构体
typedef struct
{
uint8  start_byte;//0x2
uint8 addr;
uint8 update_byte;//0x35
uint8 type; //software or font
char data_length[8];
char s_data_pack_sn[8];
uint8 data[512];
uint8 end_byte;//0x3
uint8 check_sum1;
uint8 check_sum2;
}update_soft_datapack_t;

我写的对应的C#结构体为
[StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct update_soft_start_t
        {
            public byte start_byte;//0x2
            public byte addr;
            public byte update_byte;//0x35
            public byte type; //software or font
            public byte first_or_second;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] // 大小为8
            public char[]  data_pack_num;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] // 大小为8
            public char[] sw_length;
            public byte end_byte;//0x3
            public byte check_sum1;
            public byte check_sum2;
        }

用该结构体接收调用C++DLL中返回的值就会报错:
未处理的“System.Runtime.InteropServices.MarshalDirectiveException”类型的异常出现在 Demo.exe 中。
其他信息: 方法的类型签名与 PInvoke 不兼容。
代码如下:
C#

[StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct update_soft_start_t
        {
            public byte start_byte;//0x2
            public byte addr;
            public byte update_byte;//0x35
            public byte type; //software or font
            public byte first_or_second;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] // 大小为8
            public char[]  data_pack_num;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] // 大小为8
            public char[] sw_length;
            public byte end_byte;//0x3
            publi