void * target
uint32 * decPacket = (uint32 *)target;
所以在C#中,它会像这样...
byte[] target;
UInt32[] decPacket = (UInt32[])target;
无法将 byte[] 类型转换为 uint[] 类型
如何将 C++ 中的内存对齐方式转换为 C# 中的数组?
void * target
uint32 * decPacket = (uint32 *)target;
byte[] target;
UInt32[] decPacket = (UInt32[])target;
无法将 byte[] 类型转换为 uint[] 类型
如何将 C++ 中的内存对齐方式转换为 C# 中的数组?
使用Buffer.BlockCopy
可能会更接近预期:
uint[] decoded = new uint[target.Length / 4];
Buffer.BlockCopy(target, 0, decoded, 0, target.Length);
请注意,BlockCopy
的最后一个参数始终是要复制的字节数,而不管您要复制的类型。
在C#中,您不能将 byte
数组视为 uint
数组(至少在安全代码中不行;我不知道在不安全代码中是否可以),但是 Buffer.BlockCopy
将会将 byte
数组的内容填充到 uint
数组中... 后果取决于系统的字节顺序。个人而言,我不喜欢这种方法 - 当您转移到具有不同内存布局的系统时,这样的代码容易出错。我更喜欢在协议中明确指定。但愿这个提示对您有所帮助。
正如Jon所提到的那样, Buffer.BlockCopy可以很好地用于复制此内容。
然而,如果这是一个交互操作场景,并且您想要直接访问字节数组作为uint[]
,最接近C++方法的做法是使用不安全代码:
byte[] target;
CallInteropMethod(ref target);
fixed(byte* t = target)
{
uint* decPacket = (uint*)t;
// You can use decPacket here the same way you do in C++
}
我个人更喜欢复制数据,但如果你需要避免实际复制数据,这种方法可以让你在不安全的上下文中工作。
CallInteropMethod
? - SSpokeCallInteropMethod
只是在说“这是要填充 byte[] 的内容” - 通常,在纯托管代码中不会使用它... - Reed Copsey您可以使用Buffer.BlockCopy
。与Array.Copy
不同,BlockCopy
进行字节级别的复制,而不检查数组类型是否完全兼容。
像这样:
uint[] array = new uint[bytes.Length/4];
Buffer.BlockCopy(bytes, 0, array, 0, bytes.Length);
BlockCopy
函数的参数长度是以字节为单位指定的。 - thecoop虽然有些晚,但也许这会对其他人有所帮助。(这也是比较新的方法。)
我们可以使用新的Span<>在.Net Core 2.1或更高版本中进行类似于c++风格的reinterpret cast。由于没有堆内存分配,因此速度非常快。
Span<byte> byteArray = MemoryMarshal.AsBytes<uint>(uIntArray);
// with span we can get a byte, set a byte, iterate, and more.
byte someByte = byteSpan[2];
byteSpan[2] = 33;
byte[] byteArray = MemoryMarshal.AsBytes<uint>(uIntArray).ToArray();
我使用了BitConverter.ToUInt32() - https://learn.microsoft.com/zh-cn/dotnet/api/system.bitconverter.touint32?view=netcore-3.1
byte[] source = new byte[n];
UInt32 destination;
destination = BitConverter.ToUInt32(source, 0);
对我来说似乎工作得很好。
Uint32[] res = new Uint32[target.Length];
for(int i = 0;i <= target.Length;i++)
{
res[i] = Convert.ToUint32(target[i]);
}
这是来自MSDN的官方链接。 http://msdn.microsoft.com/en-us/library/469cwstk.aspx
UInt32
。但是我必须把2个字节变成1个uint
。 - SSpokenew Uint32[target.length]
应该改为 new Uint32[target.length / sizeof(UInt32)]
。 - SSpoke