2009-12-27 109 views
0

如何從C++ dll調用中讀取C#中的錯誤字符串?如何從指針讀取字符串緩衝區中的C#

// 
// PARAMETERS: 
//  objptr 
//   Pointer to class instance. 
// 
//  pBuffer 
//   Pointer to buffer receiving NULL terminated error message string. 
//   If this value is zero, the function returns the required buffer size, in bytes, 
//   and makes no use of the pBuffer. 
// 
//  nSize 
//   Size of receiving buffer. 
//   If this value is zero, the function returns the required buffer size, in bytes, 
//   and makes no use of the pBuffer. 
// 
// RETURN VALUES: 
//  If pBuffer or nSize is zero, the function returns the required buffer size, in bytes. 
//  If the function succeeds, the return value is number of bytes copied into pBuffer. 
//  If function fails return value is 0. 
// 
extern unsafe int GetError(uint objptr, byte* pBuffer, int nSize); 

謝謝!

回答

2
byte[] buffer = new byte[1000]; 
int size; 
unsafe 
{ 
    fixed (byte* p = buffer) 
    { 
    size = GetError(???, p, buffer.Length); 
    } 
} 
string result = System.Text.Encoding.Default.GetString(buffer, 0, size); 
+0

我用GetError(???,NULL,0)來獲得郵件大小,以創建緩衝區,還努力完善。謝謝! –

+0

您也可以嘗試將byte *更改爲StringBuilder,並通過它來避免不安全的代碼。 –

+0

@Mikael:我該怎麼做? dll方法期望字節* –

0

Marshal.AllocHGlobal(int) plus Marshal.PtrToStringAuto(IntPtr, int)也許?

一些代碼方面將是很好的,因爲我假設你用對已經強迫byte*IntPtr /調用或其他一些掛羊頭賣狗肉。

基本上,調用你的函數來獲取緩衝區大小,使用AllocHGlobal()分配緩衝區,再次調用它,讀入字符串,然後釋放緩衝區(使用Marshall.FreeHGlobal(IntPtr))。這是假設你可以使用馬歇爾的分配器,當然。

相關問題