问题
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);
回答1:
Your code has a number of mistakes:
- It is pointless to set
CharSet
since there is no text here. - You specify
SetLastError
astrue
but I doubt that your C function does call the Win32SetLastError
function. - In C#
char
is a 2 byte text holding a UTF-16 character element. That does not batch Cchar
orunsigned char
which are 8 bit types. - Your code expects the C function to allocate a managed
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 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
.
来源:https://stackoverflow.com/questions/38146181/passing-a-char-array-from-c-sharp-to-c-dll