想要从“C ++ COM dll”回调C#方法 [英] Want to callback C# method from "C++ COM dll"
本文介绍了想要从“C ++ COM dll”回调C#方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从C ++ COM dll回调C#方法,这是我采取的策略。
步骤1:在C ++中 idl中的Server.dll 我声明了2级Class1和Class2,如下所示。
I want to callback C# method from "C++ COM dll", Here is the strategy I took.
Step 1:In C++ Server.dll in idl I declared 2 class Class1 and Class2 as below.
[
object,
uuid(54120D45-09DE-4e61-AA30-858CE4C472B5),
oleautomation,
helpstring("Class1 Interface"),
pointer_default(unique)
]
interface IClass1 : IUnknown
{
[helpstring("GetCls2Ptr")] HRESULT GetClass2InterfacePtr(IClass2 * ptrCls);
[helpstring("SayHellow")] HRESULT SayHellow();
}
interface IClass2 : IUnknown
{
[helpstring("CallMe")] HRESULT CallMe();
}
In Class1.h
class Class1 :public IClass1
{
IClass2 **class2Obj;
STDMETHOD GetClass2InterfacePtr(IClass2 * ptrCls)
{
class2Obj= (&ptrCls);
return S_OK;
}
STDMETHOD SayHellow(void)
{
(*class2Obj)->CallMe();
return S_OK;
}
}
第2步:
Step 2:
TlbImp c:\Server.tlb to generate Managed dll [ServerManaged.dll].
步骤3:
Step 3:
refer ServerManaged.dll in C#
步骤4:
Step 4:
In C# I declared 1 class as below
using ServerManaged;
namespace Test1
{
public class CSClass : IClass2
{
IClass1 IClass1Obj=null;
public CSClass()
{
//initialising IClass1Obj
//some code
//Set Interface objet back to C++
IClass1.GetClass2InterfacePtr(this);
//call SayHellow, which inturn will call CallMe() on this
IClass1.SayHellow();
}
void CallMe()
{
MessageBox.Show("Hurray I got a call!!");
}
}
第5步:
我的代码编译正常,运行正常,执行正常,没有异常报告
Step 5:
I code is compiling fine, running fine, executing fine, No exception reported
But the problem is I can't say "Hurray I got a call!!" :(
提前致谢
Thanks in advance
推荐答案
如果你只想设置一个回调函数,那就很容易了,如我的文章中所述。
文章如何制作C ++类。
If you only what to set a callback function it is fairly easy, as described in my article.
A more complex scenario with classes is in the article How to Marshal a C++ Class displayed.
这篇关于想要从“C ++ COM dll”回调C#方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文