Main Content

Call COM Objects in Visual C++ Programs

Note

You must choose a Microsoft® compiler to compile and use any COM object.

Use the COM object you have created as follows:

  1. Create a Visual C++® program in a file named matlab_com_example.cpp with the following code:

    #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. In the MATLAB® Command Window, compile the program as follows:

    mbuild matlab_com_example.cpp

When you run the executable, the program displays two numbers and their sum, as returned by the COM object’s adddoubles.