I am new to .NET compact framework. I need to call a DeviceIoControl function and pass structures as input and output parameters to the IOControl function.
In PInvoke/DeviceIoControl I found how to get access to the function itself. But how can I pass a pointer the structure as InBuf
and OutBuf
parameter?
The DeviceIoControl is defined as P/Invoke:
[DllImport("coredll", EntryPoint = "DeviceIoControl", SetLastError = true)]
internal static extern int DeviceIoControlCE(
int hDevice, int dwIoControlCode,
byte[] lpInBuffer, int nInBufferSize,
byte[] lpOutBuffer, int nOutBufferSize,
ref int lpBytesReturned, IntPtr lpOverlapped);
The structures in question have this layout:
struct Query
{
int a;
int b;
char x[8];
}
struct Response
{
int result;
uint32 success;
}
void DoIoControl ()
{
Query q = new Query();
Response r = new Response();
int inSize = System.Runtime.InteropServices.Marshal.SizeOf(q);
int outSize = System.Runtime.InteropServices.Marshal.SizeOf(r);
NativeMethods.DeviceIoControlCE((int)handle, (int)IOCTL_MY.CODE,
ref q, inSize, ref r, outSize, ref bytesReturned, IntPtr.Zero);
}
Edit: When I try to compile this code I get the error:
cannot convert from 'ref MyNamespace.Response' to 'byte[]'
How can I pass the address of the struct to the DeviceIoControl function what expects a pointer to byte instead of struct ref?
The issue is that your P/Invoke declaration doesn't match your call. DeviceIoControl takes in pointers for the in/out paramters:
So you can "adjust" your declaration in a lot of ways. The one in the link you provide uses a
byte[]
probably for convenience where they were using it. In your case, since you're passing simple structs (i.e. no internal pointers to other data), then the easiest "fix" is to just change you P/Invoke declaration:And you code should work. Note I also changed the types of the first two parameters to allow making your calling code more clear without casts.
EDIT 2
If you find you need different signatures, simply overload the P/Invoke. For example, the Smart Device Framework code has at least 11 overloads for DeviceIoControl. Here are just some of them to give you a flavor: