日期:2014-05-18  浏览次数:20782 次

C++中传过来的数组到C#中转换的问题
C++中:
struct test
{
WORD wHeader;
DWORD nSize;
DWORD nID;
char cCmd;
//char sDevID[16];
};
C#中:
public struct test
{
  public UInt16 wHeader;
  public UInt32 dwSize;
  public UInt32 dwID;

  public Char cCmd;
  //public string sDevID;

// C++的回调函数传过来的结构 p
public static int CallbackTestOK(IntPtr p, Int32 nEvt)
{
test t= (test)Marshal.PtrToStructure(p, typeof(FS_PACKET));
}
当结构中没有char sDevID[16]时没有问题,但是当添加了sDevID的定义后不知道C#中应该如何定义,
比如使用string或Byte[] p;p = new Byte[16];都不行啊???谁知道如何定义???

------解决方案--------------------
C# code

public struct test
{
    public UInt16 wHeader;
    public UInt32 dwSize;
    public UInt32 dwID;

    public Char cCmd;
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
    public Char[] sDevID;
}

------解决方案--------------------
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]定义长度
------解决方案--------------------
试试这个
C# code

  /// char[16]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=16)]
    public string sDevID;

------解决方案--------------------
C# code
[StructLayout(LayoutKind.Sequential)]
public struct test
{
    public ushort wHeader;
    public uint dwSize;
    public uint dwID;
    public byte cCmd;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public byte[] sDevID;
}