如何在C#中将byte[]转换为sbyte*?

5

我有一个函数需要接收sbyte*缓冲区,如何在C#中从头开始创建它,或者从现有的byte[]创建它?

2个回答

6
// Allocate a new buffer (skip this if you already have one)
byte[] buffer = new byte[256];
unsafe
{
    // The "fixed" statement tells the runtime to keep the array in the same
    // place in memory (relocating it would make the pointer invalid)
    fixed (byte* ptr_byte = &buffer[0])
    {
        // Cast the pointer to sbyte*
        sbyte* ptr_sbyte = (sbyte*) ptr_byte;

        // Do your stuff here
    }

    // The end of the "fixed" block tells the runtime that the original array
    // is available for relocation and/or garbage collection again
}

3

将其转换为数组,然后将其转换为byte[]即可。

byte[] unsigned = { 0, 1, 2 };

sbyte[] signed = (sbyte[])(Array)unsigned;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接