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

风格不统一 提交于 2020-02-04 05:06:11

问题


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 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.



来源:https://stackoverflow.com/questions/38146181/passing-a-char-array-from-c-sharp-to-c-dll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!