C# C中的结构封送处理#
我在C中有以下结构# 我用来将其转换为字节数组[]的函数是C# C中的结构封送处理#,c#,arrays,interop,struct,marshalling,C#,Arrays,Interop,Struct,Marshalling,我在C中有以下结构# 我用来将其转换为字节数组[]的函数是 static byte[] structtobyte(object obj) { int len = Marshal.SizeOf(obj); byte[] arr = new byte[len]; IntPtr ptr = Marshal.AllocHGlobal(len); Marshal.StructureToPtr(obj, ptr, true);
static byte[] structtobyte(object obj)
{
int len = Marshal.SizeOf(obj);
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
当我编译它时
Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
有什么问题吗?
提前谢谢 您报告为编译错误的错误实际上是一个运行时错误(一个
ArgumentException
)。当您想使用structtobyte
将控件
转换为字节[]
时,应该向该方法传递对控件
的引用,而不是字节
数组(字节[]
)
SizeOf
在阵列上不起作用。请改用array.Length*Marshal.SizeOf(elementType)
。您的代码工作正常,问题一定在其他地方,很可能您正在尝试转换其他类型。我正在转换我的结构,问题是结构中的字节数组。不是。我试过你的代码,它的工作方式和你发布的一样。是的,但我不认为这有什么区别。为什么字节数组在结构中是固定的,你想要一个固定的相对位置,而不是绝对位置。它仍然是一个引用,而不是字节,因为struct在编译时不知道数组的大小。另外,它不应该有一个MarshalAsAttribute吗?控制cnt;结构细胞;我正在将我编辑的cnt结构传递给它,它充满了数据。您没有提供堆栈跟踪/异常位置,但您得到的异常很可能来自marshall.SizeOf
。异常消息清楚地表明您正在提供字节数组。这就是我的答案,那就是!我是长喷,为什么它给了我错误的大小,我的结构对象-所以原因是结构有一个数组在它…⁺¹
Type 'System.Byte[]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
control ctrl = new control();
byte[] bytes = structtobyte(ctrl);