[英]Can't convert a Marshal pointer of a struct back to struct
I'm coding a windows service that communicates with my driver, as such I'm trying to, as a test, pass a struct to it and get a returned struct. 我正在编写与驱动程序通信的Windows服务的代码,因此,我试图通过测试将结构传递给它,并获得返回的结构。
In C++ this is working however in C# I'm not being able to convert an IntPtr to Struct using Marshal and that's why I'm not able to get the struct returned from the driver. 在C ++中,这是可行的,但是在C#中,我无法使用Marshal将IntPtr转换为Struct,这就是为什么我无法从驱动程序返回结构的原因。
Struct: 结构:
[StructLayout(LayoutKind.Sequential)]
struct TestEst
{
public int value;
}
Then in my driver: 然后在我的驱动程序中:
typedef struct _TEST_EST
{
int value;
} TEST_EST, *PTEST_EST;
And the code that is going to pass the struct via an IOCTL is: 通过IOCTL传递结构的代码是:
void SendIOCTL<T>(IntPtr hDevice, uint dwIoControlCode, ref T inObj, ref T outObj)
{
IntPtr inPointer = IntPtr.Zero;
IntPtr outPointer = IntPtr.Zero;
int inObjSize = 0;
int outObjSize = 0;
uint bytesReturned = 0;
if(inObj != null)
{
inObjSize = Marshal.SizeOf(inObj.GetType());
inPointer = Marshal.AllocHGlobal(inObjSize);
Marshal.StructureToPtr(inObj, inPointer, false);
if (dwIoControlCode == TEST_CTL) // the TEST IOCTL
{
TestEst lets = new TestEst();
Logger.Log("IsNull: " + (inPointer == IntPtr.Zero));
Logger.Log("SizeObj: " + inObjSize);
Marshal.PtrToStructure(inPointer, lets);
Logger.Log("Working!: " + lets.value);
}
}
}
public void SendTest()
{
TestEst request = new TestEst();
TestEst result = new TestEst();
request.value = 30;
SendIOCTL(hDriver, TEST_CTL, ref request, ref result);
Logger.Log("RA: " + result.value + " " + request.value);
}
Logger.Log() simply writes an entry to the windows event viewer. Logger.Log()只需将一个条目写入Windows事件查看器。
I omitted the actual DeviceIoControl because that's not where this fails, what is happening is in the 我省略了实际的DeviceIoControl,因为这不是失败的地方,发生的是
Marshal.PtrToStructure(inPointer, lets);
Is causing my service to show this in the logs: 导致我的服务在日志中显示此内容:
And the inPointer is not null and inObjSize is 4 而且inPointer不为null,inObjSize为4
I also tried removing the T, A from the SendIOCTL and placing only T but it's the same. 我还尝试过从SendIOCTL中删除T,A并仅放置T,但这是相同的。
Thanks in advance 提前致谢
To marshal pointer to structure use this approach 要编组结构指针,请使用此方法
var test = (T) Marshal.PtrToStructure(inPointer, typeof(T));
Do not forget to use Marshal.FreeHGlobal(inPointer)
when you're done with our allocated memory blocks. 完成分配的内存块后,不要忘了使用
Marshal.FreeHGlobal(inPointer)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.