Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a char array from c# to c++ dll

I have a dll of the LZ4 c implementation and I want to call the

LZ4_compress_default(const char* source,char* dest,int sourceLength,int maxdestLength);

function from a c# code. The function compresses the source array into the dest array. How to do this?

My C# code:

DllImport(@"CXX.dll", CharSet = CharSet.Ansi, SetLastError = true, 
    CallingConvention = CallingConvention.Cdecl)] 
internal static extern int LZ4_compress_default(
    [MarshalAs(UnmanagedType.LPArray)] char[] source, out byte[] dest, 
    int sourceSize, int maxDestSize); 


byte[] result= new byte[maxSize]; 
int x = LZ4_compress_default(array, out result, size, maxSize); 
like image 898
Sayantan Ghosh Avatar asked Mar 12 '23 20:03

Sayantan Ghosh


1 Answers

Your code has a number of mistakes:

  • It is pointless to set CharSet since there is no text here.
  • You specify SetLastError as true but I doubt that your C function does call the Win32 SetLastError function.
  • In C# char is a 2 byte text holding a UTF-16 character element. That does not batch C char or unsigned char which are 8 bit types.
  • Your code expects the C function to allocate a managed byte[], because the byte array is declared as an out parameter. Your C code cannot allocate a managed byte[]. Instead you need to have the caller allocate the array. So the parameter must be [Out] byte[] dest.

The C code should use unsigned char rather than char because you are operating on binary rather than text. It should be:

int LZ4_compress_default(const unsigned char* source, unsigned char* dest,
    int sourceLength, int maxDestLength);

The matching C# p/invoke is:

[DllImport(@"...", CallingConvention = CallingConvention.Cdecl)] 
static extern int LZ4_compress_default(
    [In] byte[] source, 
    [Out] byte[] dest, 
    int sourceLength, 
    int maxDestLength
);

Call it like this:

byte[] source = ...;
byte[] dest = new byte[maxDestLength]; 
int retval = LZ4_compress_default(source, dest, source.Length, dest.Length); 
// check retval for errors

I've guessed at the return type of the function because you omitted that in the C declaration, but your C# code suggests that it is int.

like image 115
David Heffernan Avatar answered Mar 20 '23 03:03

David Heffernan