开发者

byte[] to byte* in C#

I created 2 programs - in C# and C++, both invoke native methods from C dll. C++ works fine, because there are the same data types, C# doesn't work.

And native function parameter is unsigned char*. I tried byte[] in C#, it didn't work, then I tried:

fixed(byte* ptr = byte_array) {
  native_function(ptr, (uint)byte_array.Length);
}

It also doesn't work. Is it correct to convert byte array to byte* in such way? Is it correct to use byte in C# as unsigned char in C?

EDIT: This stuff returns the wrong result:

byte[] byte_array = Encoding.UTF8.GetBytes(source_string);
nativeMethod(byte_array, (uint)byte_array.Length);

This stuff also returns the wrong result:

 byte* ptr;
 ptr = (byte*)Marshal.AllocHGlobal((int)byte_array.Length);
 Marshal.Copy(byte_array, 0, (IntPtr)ptr, byte_array.L开发者_Python百科ength);


unsafe class Test
{
    public byte* PointerData(byte* data, int length)
    {
        byte[] safe = new byte[length];
        for (int i = 0; i < length; i++)
            safe[i] = data[i];

        fixed (byte* converted = safe)
        {
            // This will update the safe and converted arrays.
            for (int i = 0; i < length; i++)
                converted[i]++;

            return converted;
        }
    }
}

You also need to set the "use unsafe code" checkbox in the build properties.


You have to marshal the byte[] :

[DllImport("YourNativeDLL.dll")]
public static extern void native_function
(
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
    byte[] data,
    int count // Recommended
);


You could allocate an unmanaged array and use Marshal.Copy to copy the contents of the managed byte[] array to an unmanaged unsigned char* array. Note that unmanaged resources must be cleaned up manually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜