结构体中包含string数组转byte[]失败,这是为什么?

guoxijun 2011-09-10 12:41:38
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct Student
{
public int number;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 5)]
public String[] name;
}

转换函数为:
public static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structObj, structPtr, false);
Marshal.Copy(structPtr, bytes, 0, size);
Marshal.FreeHGlobal(structPtr);
return bytes;
}

总是显示int size = Marshal.SizeOf(structObj);这行错误,求指教
...全文
146 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdl2005lyx 2011-09-10
  • 打赏
  • 举报
回复
楼主,Student这个结构体,C++里是怎样定义的?
guoxijun 2011-09-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 caozhy 的回复:]

C# code
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
s……
[/Quote]
我在接收之后用这个函数解释出来是乱码
public static object BytesToStuct(byte[] bytes,Type type)
{
int size = Marshal.SizeOf(type);
if (size > bytes.Length)
{
return null;
}
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes,0,structPtr,size);
object obj = Marshal.PtrToStructure(structPtr, type);
Marshal.FreeHGlobal(structPtr);
return obj;
}

又是怎么回事?
threenewbee 2011-09-10
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StructToBytes(new Student() { name = new string[] { "123", "123", "123", "123", "123" }});
}

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct Student
{
public int number;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public String[] name;
}

public static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(structObj, structPtr, false);
Marshal.Copy(structPtr, bytes, 0, size);
Marshal.FreeHGlobal(structPtr);
return bytes;
}
}
}

110,567

社区成员

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

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

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