[英]Passing a char array from c# to c++ dll
我有一個LZ4 c實現的dll,我想調用
LZ4_compress_default(const char* source,char* dest,int sourceLength,int maxdestLength);
ac#代碼中的函數。 該函數將源數組壓縮為dest數組。 這個怎么做?
我的C#代碼:
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);
您的代碼有很多錯誤:
CharSet
毫無意義,因為這里沒有文本。 SetLastError
指定為true
但是我懷疑您的C函數是否確實調用了Win32 SetLastError
函數。 char
是2字節的文本,其中包含UTF-16字符元素。 這不會批處理8位類型的C char
或unsigned char
。 byte[]
,因為字節數組被聲明為out
參數。 您的C代碼無法分配托管byte[]
。 相反,您需要讓調用者分配數組。 因此,該參數必須為[Out] byte[] dest
。 C代碼應使用unsigned char
而不是char
因為您是在二進制而不是文本上進行操作。 它應該是:
int LZ4_compress_default(const unsigned char* source, unsigned char* dest,
int sourceLength, int maxDestLength);
匹配的C#p /調用為:
[DllImport(@"...", CallingConvention = CallingConvention.Cdecl)]
static extern int LZ4_compress_default(
[In] byte[] source,
[Out] byte[] dest,
int sourceLength,
int maxDestLength
);
這樣稱呼它:
byte[] source = ...;
byte[] dest = new byte[maxDestLength];
int retval = LZ4_compress_default(source, dest, source.Length, dest.Length);
// check retval for errors
我猜函數的返回類型是因為您在C聲明中省略了該函數,但是您的C#代碼建議它是int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.