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

c++与C#结构体转换
C++的原结构体为
typedef struct 
{
char IP[32]; //服务器地址
short port; //端口号
char group[64];
char user[64]; //登录用户名
char passwd[64]; //登录密码
} GE_SERVERPARAMETER
我转化成c#为:
  struct GE_PSERVERPARAMETER
  {
 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  public char[] IP;
  public Int16 port;
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
  public char[] group;
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
  public char[] user;
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)]
  public char[] passwd; //登录密码
}
在主程序中调用赋值:
  GE_PSERVERPARAMETER geps;
  string s = "192.168.0.11";

  geps.IP = s.ToCharArray();
  geps.group = "test";
  geps.passwd = "test";
  geps.port = 9900;
  geps.user = "test";
  bool connected = UseDll.GE_ConnectServer(m, geps);//m是我程序中的一个整型变量应该没问题
  MessageBox.Show(connected.ToString())
运行后出现错误:
未能封送类型,因为嵌入数组实例的长度与布局中声明的长度不匹配。
  于是我又改为:
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
  public string IP;
  public Int16 port;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
  public string group;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
  public string user;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
  public string passwd; //登录密码

在主程序中调用赋值:
GE_PSERVERPARAMETER geps;
  geps.IP = "122.193.4.19";
  geps.group = "test";
  geps.passwd = "gest";
  geps.port = 9900;
  geps.user = "test";
  bool connected = UseDll.GE_ConnectServer(m, geps);//m是我程序中的一个整型变量应该没问题
  MessageBox.Show(connected.ToString());
运行后出现错误“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”
搞不明白我这两种写法错在哪,应该怎么写,望高手指教


------解决方案--------------------
这是Mircrosoft P/Invoke Interop Assistant生成的
C# code

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct Anonymous_4ad7ceb4_c3e2_49fa_8fcf_dc5708e66414 {
    
    /// char[32]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=32)]
    public string IP;
    
    /// short
    public short port;
    
    /// char[64]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=64)]
    public string group;
    
    /// char[64]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=64)]
    public string user;
    
    /// char[64]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=64)]
    public string passwd;
}