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
as true
but I doubt that your C function does call the Win32 SetLastError
function.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.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With