从c++调用c#事件
Calling C# event from C++
我想知道从c++代码调用c#代码的最佳实践是什么?我到底想要什么:我已经写了c++代码,当用户使用这个程序时,遇到c++代码中的某些函数,我想调用另一个c#代码来执行其他东西,所以它就像语言之间的委托。我怎样才能最好地做到这一点?到目前为止,我的想法是:在c#中我可以创建web服务,然后用c++调用它。
我建议将c#类导出为com可见类。
这里是使用C++Cli
和boost::function
的解决方案
typedef void MemberFunctionPointerType(int x);
class NativeClass
{
public:
//I used boost but any function pointer will work
void setDelegate(boost::function<MemberFunctionPointerType> delegate)
{
m_delegate = delegate;
}
void DoSomeThing()
{
int x;
//do your logic here
...
...
...
//when the needed event occurs call the callbackfunction so the class which registered to event will get his function called.
m_delegate(x);
private:
boost::function<MemberFunctionPointerType> m_delegate;
};
托管代码:
typedef MemberFunctionPointerType* CallbackFunctionType;
delegate void CallbackFuncDelegate;
class ManagedClass
{
public:
ManagedClass()
{
m_delegate = gcnew CallbackFuncDelegate(this,&ManagedClass::CallBackFunction);
m_native = new NativeClass();
//register the delegate;
boost::function<MemberFunctionPointerType> funcPointer(static_cast<CallbackFunctionType>(Marshal::GetFunctionPointerForDelegate(m_delegate).ToPointer()));
m_native->setDelegate(funcPointer);
}
//the callback function will be called every time the nativeClass event occurs.
void CallBackFunction()
{
//do your logic or call your c# method
}
private:
CallbackFuncDelegate^ m_delegate ;
NativeClass* m_native;
};
那么为什么这个可以工作并且垃圾收集器不会破坏一切呢?在处理GC时,有两件事需要担心:
1)委托集合:只要ManagedClass还活着,委托就不会被收集。所以我们不必担心它。
2)重新分配:GC可能会在内存中重新分配对象,但本机代码不会获得指向委托的直接指针,而是指向由封送处理程序生成的一些代码块的指针。这种间接确保即使委托被移动,本机函数指针仍然有效。
尝试使用非托管导出。我个人使用它从本地c++应用程序调用c#函数。
相关文章:
- C++ MFC 跟踪事件调用
- Q维德格特关闭事件(..)未使用 QProcess::terminate() 调用
- 如何从qml Keys.oPressed调用qt keyPressEvent(QKeyEvent*事件)
- 事件上的waitforsingleobject如果调用rssetscissercrect,会导致访问违规
- 在浏览器中创建由 en 事件调用的 C# 窗口服务
- 如何在从主窗口事件处理程序调用后在子窗口中创建按钮
- 直接调用事件处理程序
- 调用 wxListCtrl::EditLabel (索引) 时无法捕获EVT_LIST_BEGIN_LABEL_EDIT事件
- 调用 Director::getInstance()->popScene() 后,调度停止以触发事件
- 对事件循环中槽的调用排队,由Qt按向后顺序处理
- 是否可以在不调用 QApplication::exec() 的情况下创建本地事件循环
- 声明在 Qt 中发生鼠标事件时调用的函数
- 我可以在不手动调整Qt大小的情况下调用调整大小事件吗?
- 如何对表中的插入事件调用 exe
- Qt从其他线程向事件循环添加函数调用
- QGraphicsScene一直在调用QGraphicsItem绘制事件
- 在插槽中调用QDialog::exec是否会阻塞主事件循环
- 如何从本机组件向C#/XAML组件进行函数调用或触发事件
- C/C++ 中事件循环的实现在调用堆栈上很好
- 从属性页的事件处理程序调用DoModal()不会弹出对话框