主要内容

extension is used on Windows在 Visual C++ 程序中调用 COM 对象

注意

您必须选择 Microsoft® 编译器来编译和使用任何 COM 对象。

按如下方式使用您创建的 COM 对象:

  1. 在名为 matlab_com_example.cpp 的文件中创建一个 Visual C++® 程序,并在其中包含以下代码:

    #include <iostream>
    using namespace std;
    
    #include "mycomponent\src\mycomponent_idl.h" 
    #include "mycomponent\src\mycomponent_idl_i.c"
    
    int main() {     
    // Initialize argument variables     
                 VARIANT x, y, out1;
    //Initialize the COM library     
                 HRESULT hr = CoInitialize(NULL);   
    //Create an instance of the COM object you created    
                 Imycomponentclass *pImycomponentclass;     
                 hr=CoCreateInstance
                   (CLSID_mycomponentclass, NULL, CLSCTX_INPROC_SERVER, 
                    IID_Imycomponentclass,(void **)&pImycomponentclass);
    // Set the input arguments to the COM method 
                 x.vt=VT_R8; 
                 y.vt=VT_R8;     
                 x.dblVal=7.3;
                 y.dblVal=1946.0;      
    // Access the method with arguments and receive the output out1 
                 hr=(pImycomponentclass -> adddoubles(1,&out1,x,y)); 
    // Print the output     
                 cout << "The input values were " << x.dblVal << " and "
                      << y.dblVal << ".\n";
                 cout << "The output of feeding the inputs into the adddoubles method is " 
                      << out1.dblVal << ".\n";      
    // Uninitialize COM     
                 CoUninitialize();     
                 return 0;
    }    
  2. 在 MATLAB® 命令行窗口中,按如下方式编译该程序:

    mbuild matlab_com_example.cpp

当您运行可执行文件时,该程序会显示两个数值及它们的和,由 COM 对象的 adddoubles 返回。