简体   繁体   English

C#调用非托管代码

[英]C# calling unmanaged code

I am trying to call unmanaged code using 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

}

C# code C#代码

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

I am having another function which returns an int value just fine, I guess it's related to LPBYTE itself. 我有另一个函数可以返回一个int值,我想它与LPBYTE本身有关。 Appreciate any help. 感谢任何帮助。

I believe you want to use 相信你要用

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

}

Note that when you call it, you will need to use Marshall.Copy to get the data out, but this will require that you know the length of the data. 请注意,在调用它时,您将需要使用Marshall.Copy来获取数据,但这将需要您知道数据的长度。

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

adam nathans book is the bible on this 亚当·内森斯的书是这本圣经

hang on: what exactly is the return value of this function. 坚持下去:该函数的返回值到底是什么。 Its a pointer to what? 它指向什么?

test points to random address, then you poke data where test points 测试点到随机地址,然后在测试点处戳数据

What do you want to return? 您想退还什么?

If you must return a pointer then declare function as returning intptr then call Marshall to copy bytes. 如果必须返回指针,则将函数声明为返回intptr,然后调用Marshall复制字节。 THen you need to decide if you need to free the returned buffer 然后,您需要确定是否需要释放返回的缓冲区

How should the .NET marshaller know how much data needs to be copied from the returned array into a managed array instance? .NET编组器应如何知道需要将多少数据从返回的数组复制到托管数组实例中?

You may want to try and accept an IntPtr as result, then use the Marshal class to copy the data. 您可能想要尝试接受一个IntPtr作为结果,然后使用Marshal类复制数据。

You should check out the pinvoke interop assistant here: 您应该在此处签出pinvoke互操作助手:

http://clrinterop.codeplex.com/ http://clrinterop.codeplex.com/

It will automatically generate pinvoke signatures for you. 它将自动为您生成pinvoke签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM