Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.Length);
like image 233
Sergey Avatar asked Jun 16 '11 08:06

Sergey


2 Answers

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.

like image 127
MrFox Avatar answered Oct 16 '22 09:10

MrFox


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
);
like image 22
user703016 Avatar answered Oct 16 '22 07:10

user703016