Byte [] in bytes * in C #

I created 2 programs - in C # and C ++, both called my own methods from the C dll. C ++ works fine because there are the same data types; C # does not work.

And the native parameter of the unsigned char* function. I tried byte[] in C #, this did not work, I tried:

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

It also does not work. Is it correct to convert byte array to byte* this way? Is it correct to use bytes in C # as an 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 material also returns an incorrect result:

  byte* ptr; ptr = (byte*)Marshal.AllocHGlobal((int)byte_array.Length); Marshal.Copy(byte_array, 0, (IntPtr)ptr, byte_array.Length); 
+4
source share
3 answers

You must make a byte[] marker:

 [DllImport("YourNativeDLL.dll")] public static extern void native_function ( [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, int count // Recommended ); 
+2
source
 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 check the "Use unsafe code" checkbox in the assembly properties.

+4
source

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

0
source

All Articles