用C#构造元帅 [英] Struct marshal in C#
本文介绍了用C#构造元帅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C#中具有以下结构
I have the following struct in C#
unsafe public struct control
{
public int bSetComPort;
public int iComPortIndex;
public int iBaudRate;
public int iManufactoryID;
public byte btAddressOfCamera;
public int iCameraParam;
public byte PresetNum;
public byte PresetWaitTime;
public byte Group;
public byte AutoCruiseStatus;
public byte Channel;
public fixed byte Data[64];
}
我用来将其转换为字节数组[]的函数是
And the function i use to convert it to byte array[] is
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.
可能是什么问题? 预先感谢!
What can be the problem? Thanks in advance!
推荐答案
SizeOf
在数组上不起作用.改为使用array.Length * Marshal.SizeOf(elementType)
.
SizeOf
doesn't work on arrays. Use array.Length * Marshal.SizeOf(elementType)
instead.
这篇关于用C#构造元帅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文