2010-12-09 179 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类来复制数据。