允许本机C++组件引发CLR异步事件

Allow native C++ components to raise CLR Asynchronous events

本文关键字:CLR 异步 事件 许本机 C++ 组件      更新时间:2023-10-16

我需要在我的本机代码中将异步事件提升到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
}

对于事件源来说,实现异步处理模型通常不是一个好主意——这会迫使客户端代码是多线程的并进行同步,并且在不同组件选择不同模型时会导致复杂性。

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