reinterpret_cast在C# [英] reinterpret_cast in C#

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

问题描述

我正在寻找一种方式重新解释一个类型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.

任何想法? / p>

Any ideas?

推荐答案

你可以实现这一点,但这是一个相对不好的想法。这样的原始内存访问不是类型安全的,只能在完全信任安全环境下完成。你不应该在一个正确设计的托管应用程序中这样做。如果你的数据伪装成两种不同的形式,也许你实际上有两个不同的数据集?

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?

在任何情况下,这里是一个快速和简单的代码片段,问:

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]);
        }
    }
}

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

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