2009-12-07 62 views
2

我在寫一個使用.NET 2.0的c#應用程序。我需要使用舊庫來進行專有壓縮。我沒有該庫的源代碼,並且它背後的開發人員已經很久沒有。將DLLImport與包含空字符的輸出char []一起使用

我的問題是生成的char []包含空值,並被截斷。下面是該函數的聲明:

[DLLImport("foo.dll")] 
public static extern bool CompressString(char[] inputValue, out char[] outputValue, uint inputLength, out uint outputLength); 

我如何可以聲明輸出的char []應該作爲一個byte []來處理,而不是空值終止的?


更多信息:

我有頭文件。這是聲明:

BOOL CompressString(char *DecompBuff, char **RetBuff, unsigned long DecompLen, unsigned long *RetCompLen); 
+0

你難道沒有一個聲明'CompressString'功能或至少一些文件頭文件描述函數的參數?你怎麼知道簽名? – 2009-12-07 17:50:05

+0

你不應該在任何地方在你的C#代碼中使用'char',而是'byte'或'sbyte'(這相當於C++'char')。 – 2009-12-07 18:24:13

回答

3

看看MSDN article在P/Invoke中傳遞數組。我認爲你可能想用SizeParamIndex來告訴編組人員哪個參數保存了傳遞數組的大小。

編輯:SizeParamIndex不幸的是不允許在outref參數。你可以,但是,手動將它複製:

[DLLImport("foo.dll")] 
public static extern bool CompressString([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)] char[] inputValue, out IntPtr outputValue, uint inputLength, out uint outputLength); 

public static bool CompressStringInvoke(char[] inputValue, out char[] outputValue, uint inputLength) { 
    IntPtr outputPtr; 
    uint outputLen; 
    if (CompressString(inputValue, out outputPtr, inputLength, out outputLen)) { 
     outputValue = new char[outputLen]; 
     Marshal.Copy(outputPtr, outputValue, 0, (int)outputLen); 
     return true; 
    } 
       outputValue = new char[0]; 
    return false; 
} 
+0

我得到這個錯誤:無法封送'參數#2':無法使用SizeParamIndex作爲ByRef數組參數。 – 2009-12-07 17:59:57

+0

對。用另一種解決方案編輯。 – Lucero 2009-12-07 18:20:25

+0

輝煌!謝謝! (我修復了一些小的語法問題) – 2009-12-07 18:22:55

相關問題