C# 中的 reinterpret_cast [英] reinterpret_cast in C#

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

问题描述

我正在寻找一种方法来将 byte[] 类型的数组重新解释为不同的类型,比如 short[].在 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?

无论如何,这里有一个快速简单的代码片段来完成您的要求:

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

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

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