允许本机C++组件引发CLR异步事件
Allow native C++ components to raise CLR Asynchronous events
我需要在我的本机代码中将异步事件提升到C#,我已经将其用作桥接CLI,实际上我已经从C++/CLI发送了一个指向函数的指针,但它不能正常工作?我需要知道:1-怎么了?2-如何使其成为异步事件以不阻止处理?在这个例子中,我需要在每次达到1000时引发一个事件,这是我的代码计数.h
typedef void pointertofunc(bool IsOverFlowOccured);
typedef pointertofunc *pointertofuncdelegate;
class count
{
public:
void startCounting(pointertofuncdelegate);
count();
~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
}
对于事件源来说,实现异步处理模型通常不是一个好主意——这会迫使客户端代码是多线程的并进行同步,并且在不同组件选择不同模型时会导致复杂性。
相反,同步调用事件,并让订阅者挂起回调并立即返回。这与客户端代码喜欢的任何异步模型都兼容,例如本机PostMessage
或Control.BeginInvoke
或TPL(async/await)或工作线程池。
相关文章:
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 如何在C++中实现带有packaged_task的异步等待循环?
- 如何停止 CLR 主机?
- 创建 Spdlog 异步文件记录器时遇到困难
- C ++异步键盘输入(标准方式)
- 在 gtkmm 中异步加载图像
- 带有 Boost.Beast 的异步读取标头
- 如何在 c++ 中异步调用静态方法?
- libcurl :C++处理多个异步请求
- 如何在C++上启动异步线程
- TCP 服务器的异步读取使用 boost::asio 打印客户端套接字发送的数据
- 增强 ASIO 和串行端口异步读取
- 使用 Qt5 SQL 进行异步数据库访问的策略
- 如何使用从处理程序调度的最终回调将响应异步返回给调用方on_read?
- C++中真正的异步文件 IO
- 提升::Asio 异步聊天客户端停止与服务器通信
- 在 c++ 托管和异步运行中调用 c# 可执行文件
- std::异步与非静态成员函数
- 允许本机C++组件引发CLR异步事件