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);
Your code has a number of mistakes:
CharSet
since there is no text here.SetLastError
astrue
but I doubt that your C function does call the Win32SetLastError
function.char
is a 2 byte text holding a UTF-16 character element. That does not batch Cchar
orunsigned char
which are 8 bit types.byte[]
, because the byte array is declared as anout
parameter. Your C code cannot allocate a managedbyte[]
. 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 thanchar
because you are operating on binary rather than text. It should be:The matching C# p/invoke is:
Call it like this:
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
.