且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

COM C#中,如何使用C ++调用COM

更新时间:2023-02-09 14:58:19

如果你的代码的工作方式,因为某处C ++项目,还有如果你定义使用下面的语句(这是一个自动 #import指令为例):

  _COM_SMARTPTR_TYPEDEF(ICalc,__uuidof(ICalc)); 



_COM_SMARTPTR_TYPEDEF是定义在 ICalc 智能指针宏code>。这是一个微软的Visual C ++更容易COM支持神奇扩展。官方文档是在这里: _com_ptr_t类




一个智能指针通常是由_COM_SMARTPTR_TYPEDEF宏提供的typedef定义
引用。这个宏接受一个
接口名称和IID并宣布_com_ptr_t
的专业化与接口的名称加上 PTR后缀


块引用>

I used a online example of C# COM and call it through C++. The following is the C# COM code, only one interface "ICalc" and one class "Calc".

namespace COMLib
{
[Guid("F40D7BC9-CF53-4613-AA5E-F269AD73808F")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ICalc
{
    [DispId(1)]
    long Factorial(int n);
}

[Guid("8EE38F2E-75BE-4B45-87B6-3F6D15FDBBC5")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(ICalc))]
[ProgId("MyCalc")]
public class Calc : ICalc
{
    long ICalc.Factorial(int n)
    {
        long fact = 1;
        for (int i = 1; i <= n; i++)
            fact *= i;
        return fact;
    }
}
}

The following code is in C++ to call this this function. It is worked. However, I am confused with the code in second line. where is the "ICalcPtr" come from? Or is this some mechanism?

CoInitialize(NULL);
    COMLib::ICalcPtr pCalc;
    HRESULT hRes = pCalc.CreateInstance(__uuidof(COMLib::Calc));
    if(FAILED(hRes))
        printf("ICalcPtr::CreateInstance failed w/err 0x%08lx\n", hRes);
    else
    {
        printf("%d\n", pCalc->Factorial(3));
    }
    system("pause");
    CoUninitialize();
    return 0;

If you code works, its because somewhere in the C++ project, there is the following statement defined (it's automatic if you used a #import directive for example):

_COM_SMARTPTR_TYPEDEF(ICalc, __uuidof(ICalc));

_COM_SMARTPTR_TYPEDEF is a macro that defines a "smart pointer" on ICalc. It's a Microsoft Visual C++ magical extension for easier COM support. The official documentation is here: _com_ptr_t Class

A smart pointer is usually referenced by the typedef definition provided by the _COM_SMARTPTR_TYPEDEF macro. This macro takes an interface name and the IID and declares a specialization of _com_ptr_t with the name of the interface plus a suffix of Ptr.