使用COM Interop从非托管C ++访问c#属性

时间:2013-06-29 05:56:35

标签: c# c++ properties com interop

我有一个带有返回类型字符串(甚至是对象)的属性,它作为get_Name和put_Name暴露在COm中.tlh文件中。如何访问它并在非托管c ++中设置此属性。 直到现在.. 在C#方面, 我通过与DispId(1)的接口公开了这个属性,并在继承该接口的类中实现了它。 在c ++(非托管端), 我使用以下语法创建了一个接口指针:

ManagedDLL::ICalculatorPtr pICalculator;//Interface having the property
hr = pICalculator.CreateInstance(__uuidof(ManagedDLL::Calculator));//1. Calculator implements property of Icalculator & hr is of HRESULT type
    pICalculator->put_Name="New1";
    pICalculator->put_Name="New2";//below error comes here :

错误C2659:'=':作为左操作数运行 我知道这个错误的意思。 仅供参考:我想在非托管c ++中设置我的Name属性时在c#中引发一个事件。

1 个答案:

答案 0 :(得分:0)

试试这个:

pICalculator->put_Name(_TEXT("New1"));

从COM导入后,您的C#属性成为方法。

<强> UPD 即可。 该示例使用_TEXT宏从char*转换为BSTR,但在ATL中也有有用的CComBSTR类型,这样可以更轻松地处理BSTR。< / p>