gpt4 book ai didi

c++ - 允许 native C++ 组件引发 CLR 异步事件

转载 作者:太空宇宙 更新时间:2023-11-04 14:31:31 24 4
gpt4 key购买 nike

我需要在我的 native 代码中向 C# 引发异步事件,我已经用作桥接 CLI,实际上我已经通过从 C++/CLI 发送指向函数的指针,但它没有正常工作?我需要知道:1-怎么了? 2-如何使异步事件不阻塞处理?在此示例中,我需要在每次达到 1000 时引发一个事件,这是我的代码计数.h

typedef void pointertofunc(bool IsOverFlowOccured);
typedef pointertofunc *pointertofuncdelegate;
class count
{

public:
void startCounting(pointertofuncdelegate);
count();
~count();
};

计数.cpp

void count::startCounting(pointertofuncdelegate)
{
for (int i = 0; i < 100000; i++)
{
//printf("%d \n", i);
if (i == 1000)
{
pointertofuncdelegate(true);
printf("%d \n", i);
i = 0;
}
}
}

CLR(.h 文件)

public delegate void manageddelegate(bool isworkflowoccured);
ref class CounterRaiseAsynchronousEvent
{
public:
event manageddelegate^ managedEventHandler;
CounterRaiseAsynchronousEvent();
void initialize();
void raiseEvent(bool eoverFlow);

private:
count* wrapperObject;
};

CLR(.cpp 文件)

    void CounterRaiseAsynchronousEvent::initialize()
{
//Create a new delegate and point it to the member function
manageddelegate^ prDel = gcnew manageddelegate(this, &CounterRaiseAsynchronousEvent::raiseEvent);
GCHandle gch = GCHandle::Alloc(prDel);
//Convert the delegate to a function pointer
IntPtr ip = Marshal::GetFunctionPointerForDelegate(prDel);
//... and cast it to the appropriate type
pointertofuncdelegate fp = static_cast<pointertofuncdelegate>(ip.ToPointer());
//set the native function pointer on the native class
wrapperObject->startCounting(fp);
}
void CounterRaiseAsynchronousEvent::raiseEvent(bool isOverflowOccurred)
{
//Do any thing
}

最佳答案

事件源实现异步处理模型通常不是一个好主意——这会强制客户端代码为多线程并进行同步,并且当不同的组件选择不同的模型时会导致复杂情况。

相反,同步调用事件,让订阅者挂起回调并立即返回。这与客户端代码喜欢的任何异步模型兼容,例如 native PostMessageControl.BeginInvoke 或 TPL (async/await) 或工作线程池。

关于c++ - 允许 native C++ 组件引发 CLR 异步事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28878294/

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