从byte []数组填充C#结构的最佳方法是什么,其中数据来自C/C++结构?C结构看起来像这样(我的C很生锈):
typedef OldStuff {
CHAR Name[8];
UInt32 User;
CHAR Location[8];
UInt32 TimeStamp;
UInt32 Sequence;
CHAR Tracking[16];
CHAR Filler[12];
}
Run Code Online (Sandbox Code Playgroud)
并填写这样的东西:
[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(0)]
public string Name;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(8)]
public uint User;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
[FieldOffset(12)]
public string Location;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(20)]
public uint TimeStamp;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(24)]
public uint Sequence;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
[FieldOffset(28)]
public string Tracking;
}
Run Code Online (Sandbox Code Playgroud)
什么是复制OldStuff到的最佳方式NewStuff,如果OldStuff作为byte []数组传递? …
我正在使用C#,而且我无法从像C++这样的特定点开始发送数组,这很烦人.
假设这段代码:
int[] array = new int[32];
foobar (array + 4); //send array starting from the 4th place.
Run Code Online (Sandbox Code Playgroud)
这是C#的一种奇怪的语法,因为我们没有任何可用的指针,但肯定有办法吗?有.Skip(),但我认为它产生了一个新的数组,这是我不喜欢的.
我有什么选择?
我有一个不同类型对象的数组,我使用BinaryWriter将每个项目转换为二进制等价物,以便我可以通过网络发送结构.
我现在做的事情就像
for ( i=0;i<tmpArrayList.Count;i++)
{
object x=tmpArrayList[i];
if (x.GetType() == typeof(byte))
{
wrt.Write((byte)x);
}
........
Run Code Online (Sandbox Code Playgroud)
问题是,如果错过了一个类型,我的代码将来可能会破坏.
我想做点什么.
object x=tmpArrayList[i];
wrt.Write(x);
Run Code Online (Sandbox Code Playgroud)
但除非我每次演员,否则它不起作用.
编辑:
在查阅答案之后,这就是我想出的功能.为了测试,该函数将数组发送到syslog.
private void TxMsg(ArrayList TxArray,IPAddress ipaddress)
{
Byte[] txbuf=new Byte[0];
int sz=0;
// caculate size of txbuf
foreach (Object o in TxArray)
{
if ( o is String )
{
sz+=((String)(o)).Length;
}
else if ( o is Byte[] )
{
sz+=((Byte[])(o)).Length;
}
else if ( o is Char[] )
{
sz+=((Char[])(o)).Length;
}
else // take care of …Run Code Online (Sandbox Code Playgroud)