C# 中的设备ioControl 会导致 998 错误:对内存位置的访问无效



>我有一个简单的C驱动程序,它接受ULONG参数。在C语言中,我使用:

unsigned long ip = atoll(argv[1]);
if (!DeviceIoControl(
DeviceHandle,
0x10,
&ip,
sizeof(ip),
NULL,
0,
&BytesReturned,
NULL
))

它运行良好,但是当我在 C# 中执行此操作时,

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DeviceIoControl([In] IntPtr hDevice,
[In] int dwIoControlCode, [In] IntPtr lpInBuffer,
[In] int nInBufferSize, [Out] IntPtr lpOutBuffer,
[In] int nOutBufferSize, out int lpBytesReturned,
[In] IntPtr lpOverlapped);
...
Int64 ip = ip2long(ipstr);
if (! Win32.DeviceIoControl(
hDevice, 0x10, 
(IntPtr) ip, Marshal.SizeOf(ip), 
IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero))
{
throw new Exception("DeviceIoControl(): " + Marshal.GetLastWin32Error());
}

它始终导致 998 错误:内存访问无效。

从 DbgView 中,呼叫从未到达驱动程序。这是怎么回事?

有趣的是,你不能直接将uint转换为IntPtr。您必须分配内存才能执行此操作:

IntPtr ipPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ip));
Marshal.WriteInt64(ipPtr, ip);

最新更新