2010-12-09 195 views
1

我想用C#調用非託管代碼。C#調用非託管代碼

extern "C" __declspec(dllexport) LPBYTE DataReceived(LPBYTE signals) 
{ 
    LPBYTE test; 
    *(WORD*)(test) = 0x0C; 
    *(WORD*)(test + 2) = 0x1000; 

    return test; 
    // I even tried returning 0x00 only; and I was still getting the exception 

} 

internal sealed class Test 
{ 
    [DllImport("testlib.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] 
    public static extern byte[] DataReceived(byte[] signals); 

} 

// signals is byte[] too 
byte[] foo = Test.DataReceived(signals); 

//exception that occurs 
A first chance exception of type 'System.Runtime.InteropServices.MarshalDirectiveException 

我有它返回一個int值就好了另一個函數的C#代碼,我想這是對自身LPBYTE相關。感謝任何幫助。

回答

3

我相信你想使用

internal sealed class Test 
{ 
    [DllImport("testlib.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] 
    public static extern IntPtr DataReceived(byte[] signals); 

} 

注意,當你調用它,你將需要使用Marshall.Copy獲取數據,但是這需要你知道數據的長度。

IntPtr fooPtr = Test.DataRecieved(signals); 
var foo = new byte[LENGTH]; 
Marshall.Copy(fooPtr, foo, 0, LENGTH); 
+0

得到它的工作,輝煌。謝謝。 – unmanageddude 2010-12-09 00:30:53

0

亞當納森·本書是關於這個

聖經掛在:究竟是這個函數的返回值。它指向什麼?

測試點的隨機地址,那麼你就戳在那裏測試點

你怎麼想返回的數據?

如果您必須返回一個指針,然後聲明函數返回intptr然後調用Marshall複製字節。您需要決定是否需要釋放返回的緩衝區

0

.NET marshaller應該如何知道需要將多少數據從返回的數組複製到託管數組實例中?

您可能想嘗試並接受IntPtr作爲結果,然後使用Marshal類來複制數據。

相關問題