C#ポインタとバイト配列の操作

1989 ワード

private static byte[] ReadBytesFromPtr(IntPtr intPtr, int bufferLength)

{

    var result = new byte[bufferLength];

    var count = bufferLength;

    for (var i = 0; i < bufferLength; i++)

    {

        result[i] = Marshal.ReadByte(intPtr, i);

        if (result[i] == 0)

        {

            count = i;

            break;

        }

    }

    return result.Take(count).ToArray();

}

private static void WriteBytesToPtr(IntPtr intPtr, byte[] bytes)

{

    int j;

    for (j = 0; j < bytes.Length; j++)

    {

        Marshal.WriteByte(intPtr, j, bytes[j]);

    }

    Marshal.WriteByte(intPtr, j, 0);

}