gpt4 book ai didi

C# 和 native 重叠 I/O

转载 作者:行者123 更新时间:2023-11-30 19:50:40 29 4
gpt4 key购买 nike

我有一个正在包装的 C dll,以便我可以从 C# 调用它。一个函数使用事件在状态发生变化时通知您,并且想办法处理它需要一些挖掘。它似乎工作正常,但我很好奇是否有人比我有更多的经验并且可以提供任何建议。

函数在dll的.h文件中定义为:

int NotifyStateChange(OVERLAPPED *overlapped);  
typedef int (*NOTIFY_STATE_CHANGE_PROC)(OVERLAPPED *);

调用它的示例 C 代码:

OVERLAPPED overlapped;  
overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
fns.NotifyStateChange(&overlapped);
WaitForSingleObject(overlapped.hEvent, INFINITE);
// ...query for the new state or whatever...

这就是我在 C# 中处理它的方式:

[DllImport("myfuncs.dll")]
unsafe public static extern int NotifyStateChange(NativeOverlapped* lpOverlapped);

static private ManualResetEvent m_stateChangeEvent = new ManualResetEvent(false);

public static DeviceState WaitForStateChange()
{
unsafe
{
Overlapped overlapped = new Overlapped(0, 0,
m_stateChangeEvent.SafeWaitHandle.DangerousGetHandle(), null);
IOCompletionCallback callback = StateChangeCallback;
byte[] userData = new byte[100];
NativeOverlapped* nativeOverlapped = overlapped.Pack(callback, userData);
NotifyStateChange(nativeOverlapped);
m_stateChangeEvent.WaitOne();
Overlapped.Unpack(nativeOverlapped);
Overlapped.Free(nativeOverlapped);
}
return GetCurrentState();
}

[ComVisibleAttribute(true)]
unsafe static public void StateChangeCallback (
uint errorCode,
uint bytesTransferred,
NativeOverlapped* overlapped)
{
m_stateChangeEvent.Set();
}

我不清楚的一件事是对 userData 的需求。 NotifyStateChange 只是触发一个事件,它不返回任何数据。将 null userData 传递给 Pack() 似乎工作正常,但我担心 userData 可能会在我不知道的情况下发生某些事情。

如果有任何更合适的方法来执行此操作,我将不胜感激。

埃里克

最佳答案

是的 - 这正是我向 stackoverflow 提出难题的原因。现在看起来很明显。这是简化得多的代码...

    [DllImport("myfuncs.dll")]
public static extern int NotifyStateChange(ref NativeOverlapped lpOverlapped);

public static DeviceState WaitForStateChange()
{
ManualResetEvent stateChangeEvent = new ManualResetEvent(false);
NativeOverlapped nativeOverlapped = new NativeOverlapped();
nativeOverlapped.EventHandle =
stateChangeEvent.SafeWaitHandle.DangerousGetHandle();
NotifyStateChange(ref nativeOverlapped);
stateChangeEvent.WaitOne();

return GetCurrentState();
}

谢谢!

埃里克

关于C# 和 native 重叠 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1982495/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com