byte[] to byte* in C#

18,123

Solution 1

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

Solution 2

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.

Share:
18,123
Sergey
Author by

Sergey

I'm a student.

Updated on June 12, 2022

Comments

  • Sergey
    Sergey almost 2 years

    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);
    
  • user1703401
    user1703401 almost 13 years
    LPArray is the default marshaling, this is unlikely to help the OP.