C# calling unmanaged code
I am trying to call unmanaged code using 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
internal sealed class Test
{
[DllImport("testlib.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpellin开发者_开发百科g = 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. 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.
IntPtr fooPtr = Test.DataRecieved(signals);
var foo = new byte[LENGTH];
Marshall.Copy(fooPtr, foo, 0, LENGTH);
How should the .NET marshaller know how much data needs to be copied from the returned array into a managed array instance?
You may want to try and accept an IntPtr
as result, then use the Marshal
class to copy the data.
You should check out the pinvoke interop assistant here:
http://clrinterop.codeplex.com/
It will automatically generate pinvoke signatures for you.
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. THen you need to decide if you need to free the returned buffer
精彩评论