如何将c++的struct表示为C#,并把 bytes? Marshal的方式仅支持简单类型,不支持char A[20]的形式。

tyzyx 2007-08-11 11:49:16
C++的结构体如下,需要用C#表示这个结构体并转为byte数组用TcpClient发送。

struct test
{
unsigned long ID;
char A[20];
char B[20];
};
表示为C#为,表示的对否?如果不对,应如何表示?
public struct test
{
public uint ID;
public char[] A;
public char[] B;
}
在网上找到将上面结构体转为byte的方法如下
test temp ;
temp.ID =100;
temp.A = new char[20];
temp.B = new char[20];

int rawsize = 45;// Marshal.SizeOf(test);
IntPtr buffer = Marshal.AllocHGlobal(1024);
Marshal.StructureToPtr(temp, buffer, false);//这句会崩溃~~~
byte[] rawdatas = new byte[rawsize];
Marshal.Copy(buffer, rawdatas, 0, rawsize);


这个方法用的对吗?还有其它方法转换吗?
...全文
344 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
tyzyx 2007-08-11
  • 打赏
  • 举报
回复
#region
[StructLayout(LayoutKind.Sequential, Pack = 1)]
//[StructLayout(LayoutKind.Explicit)]
public struct MsgCOMContent
{
//[FieldOffset(0)]
public uint ID;
//[FieldOffset(4)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 21 )]
//[FieldOffset(4), MarshalAs(UnmanagedType.ByValArray, SizeConst = 21)]
public char[] A;
//[FieldOffset(25)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 70)]
//[FieldOffset(25), MarshalAs(UnmanagedType.ByValArray, SizeConst = 70)]
public char[] B;
}
#endregion

自己解决
AptSnail 2007-08-11
  • 打赏
  • 举报
回复
学习
真相重于对错 2007-08-11
  • 打赏
  • 举报
回复
ms-help://MS.MSDNQTR.2003FEB.2052/cpguide/html/cpconarrayssample.htm
真相重于对错 2007-08-11
  • 打赏
  • 举报
回复
sf

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧