reinter在C#pret_cast [英] reinterpret_cast in C#

查看:224
本文介绍了reinter在C#pret_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来reinter preT类型为byte []数组为不同类型,说短[]。在C ++中,这将通过一个简单的投来实现,但是在C#中我还没有找到一种方法来实现这一目标而不诉诸复制整个缓冲区。

I'm looking for a way to reinterpret an array of type byte[] as a different type, say short[]. In C++ this would be achieved by a simple cast but in C# I haven't found a way to achieve this without resorting to duplicating the entire buffer.

任何想法?

推荐答案

可以做到这一点,但是这是一个比较糟糕的主意。这样原始内存访问是类型安全的,只能完全信任的安全环境下进行。你不应该在一个设计合理的托管应用程序做到这一点。如果您的数据是根据两种不同形式的伪装,也许你实际上有两个不同的数据集?

You can achieve this but this is a relatively bad idea. Raw memory access like this is not type-safe and can only be done under a full trust security environment. You should never do this in a properly designed managed application. If your data is masquerading under two different forms, perhaps you actually have two separate data sets?

在任何情况下,这里是一个快速而简单code片段来完成你的要求:

In any case, here is a quick and simple code snippet to accomplish what you asked:

byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int byteCount = bytes.Length;

unsafe
{
    // By using the fixed keyword, we fix the array in a static memory location.
    // Otherwise, the garbage collector might move it while we are still using it!
    fixed (byte* bytePointer = bytes)
    {
    	short* shortPointer = (short*)bytePointer;

    	for (int index = 0; index < byteCount / 2; index++)
    	{
    		Console.WriteLine("Short {0}: {1}", index, shortPointer[index]);
    	}
    }
}

这篇关于reinter在C#pret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆