Main Content

Publish MATLAB Interface to C++ Library Programmatically

R2026b

This example shows how to programmatically create a MATLAB® interface to a C++ library declared in the header file matrixOperations.hpp and defined in the C++ source file matrixOperations.cpp. You can save the MATLAB commands from this example in a workflow script—for example, publishmatrix.m—which you can modify with updates and future enhancements or integrate with a CI (continuous integration) workflow.

View C++ Header and Source Files

To view the C++ header and source files that define the C++ library used in this example, open the matrixOperations.hpp and matrixOperations.cpp files provided by MATLAB. The startpath variable contains the library start path.

startpath = fullfile(matlabroot,"extern","examples","cpp_interface");
edit(fullfile(startpath,"matrixOperations.hpp"));
edit(fullfile(startpath,"matrixOperations.cpp"));

For more information about header and source files and compiler dependencies, see Requirements for Building a MATLAB Interface to C/C++ Libraries.

Create Interface Configuration

Configure a MATLAB interface to a C++ library by creating a clibgen.api.InterfaceConfiguration object with the interface configuration as input. For this example, specify the interface name as matrix and set the location of the header file.

icfg = clibgen.api.InterfaceConfiguration("matrix");
icfg.HeaderFiles = fullfile(startpath,"matrixOperations.hpp");

Create Interface Definition

Define the MATLAB interface by creating a clibgen.api.InterfaceDefinition object. Set the locations of the source file and library file.

idef = clibgen.api.InterfaceDefinition(icfg);
idef.SourceFiles = fullfile(startpath,"matrixOperations.cpp");
if ispc
  idef.Libraries = fullfile(startpath,"win64","mingw64","matrixOperations.lib");
elseif ismac
  idef.Libraries = fullfile(startpath,"maca64","matrixOperations.dylib");
elseif isunix
  idef.Libraries = fullfile(startpath,"glnxa64","matrixOperations.so");
end

Display the interface definition. In some cases, MATLAB cannot automatically provide complete construct definitions, typically because pointer-based arguments have ambiguous array sizes. You must provide the missing size information before you can build the interface. For this example, the IncompleteClasses and IncompleteFunctions properties indicate constructs that need definition.

idef
idef = 
  Buildable InterfaceDefinition with properties:

                 Classes: [1×1 clibgen.api.ClassDefinition]
               Functions: [1×3 clibgen.api.FunctionDefinition]
                   Enums: [1×0 clibgen.api.EnumDefinition]

           InterfaceName: "matrix"
               Libraries: "C:\Program Files\MATLAB\R2026b\matlab\extern\examples\cpp_interface\win64\mingw64\matrixOperations.lib"
             SourceFiles: "C:\Program Files\MATLAB\R2026b\matlab\extern\examples\cpp_interface\matrixOperations.cpp"

       IncompleteClasses: [1×1 clibgen.api.ClassDefinition]
     IncompleteFunctions: [1×2 clibgen.api.FunctionDefinition]

      UnsupportedClasses: [1×0 clibgen.api.UnsupportedClass]
    UnsupportedFunctions: [1×0 clibgen.api.UnsupportedFunction]

  Show all properties

Define Incomplete Class

Identify the incomplete class.

idef.IncompleteClasses
ans = 
  ClassDefinition with properties:

                    CPPName: "Mat"
                 MATLABName: "clib.matrix.Mat"
       HasIncompleteMembers: true
    IsConstructibleInMATLAB: true
                   Included: true

  Show all properties

Click the Show all properties link.

                   CPPName: "Mat"
                 MATLABName: "clib.matrix.Mat"
               Constructors: [1×2 clibgen.api.ConstructorDefinition]
                    Methods: [1×4 clibgen.api.MethodDefinition]
                 Properties: [1×0 clibgen.api.PropertyDefinition]
     IncompleteConstructors: [1×0 clibgen.api.ConstructorDefinition]
          IncompleteMethods: [1×3 clibgen.api.MethodDefinition]
       IncompleteProperties: [1×0 clibgen.api.PropertyDefinition]
       HasIncompleteMembers: true
    IsConstructibleInMATLAB: true
                Description: "clib.matrix.Mat    Representation of C++ class Mat."
        DetailedDescription: ""
                   Included: true

The Mat class has three incomplete methods listed in the IncompleteMethods property.

clsDef = idef.findClass("Mat");
clsDef.IncompleteMethods
ans = 
  1×3 MethodDefinition array with properties:

    CPPName
    MATLABName
    Overloaded
    OwningClassName
    CPPSignature
    MATLABSignature
    CPPInputs
    CPPOutput
    Status
    Included

  Display as table

Click the Display as table link to identify the methods.

    CPPName     MATLABName    Overloaded      Status      Included
    _________    __________    __________    __________    ________

    "setMat"     "setMat"        false       Incomplete     false  
    "getMat"     "getMat"        false       Incomplete     false  
    "copyMat"    "copyMat"       false       Incomplete     false  

Define setMat Method

Display the properties of the setMat method.

methDef = clsDef.findMethod("setMat")
methDef = 

  MethodDefinition with properties:

            CPPName: "setMat"
         MATLABName: "setMat"
         Overloaded: false
    OwningClassName: "Mat"
       CPPSignature: "void Mat::setMat(int [] src,size_t len)"
    MATLABSignature: <Define incomplete inputs to see the MATLAB signature.>
          CPPInputs: [1×2 clibgen.api.InputArgumentDefinition]
          CPPOutput: [1×0 clibgen.api.OutputArgumentDefinition]
             Status: Incomplete
           Included: false

  Show all properties

The MATLABSignature property shows that you must define incomplete inputs to see the MATLAB signature. Inspect the inputs.

methDef.CPPInputs
ans = 

  1×2 InputArgumentDefinition array with properties:

    Name
    Position
    CPPType
    MATLABType
    Direction
    Size
    Status

  Display as table

Click the Display as table link to identify the incomplete inputs. In this example, the src argument is incomplete.

    Name     Position    CPPType                MATLABType                  Status  
    _____    ________    ________    _________________________________    __________

    "src"       1        "int []"    "clib.array.matrix.Int"              Incomplete
    "len"       2        "size_t"    "uint64"                             Complete  

Display the signature to see how the method uses the argument.

methDef.CPPSignature
ans = 

    "void Mat::setMat(int [] src,size_t len)"

Because the src argument is a pointer, MATLAB cannot automatically determine the size of src. Define src as an input array whose size is the len argument.

argDef = methDef.CPPInputs([methDef.CPPInputs.Name] == "src");
argDef.define(Size="len");

Verify that the setMat method is completely defined.

methDef
methDef = 

  MethodDefinition with properties:

            CPPName: "setMat"
         MATLABName: "setMat"
         Overloaded: false
    OwningClassName: "Mat"
       CPPSignature: "void Mat::setMat(int [] src,size_t len)"
    MATLABSignature: clib.matrix.Mat/setMat(src)
          CPPInputs: [1×2 clibgen.api.InputArgumentDefinition]
          CPPOutput: [1×0 clibgen.api.OutputArgumentDefinition]
             Status: Complete
           Included: true

  Show all properties

Define getMat Method

Follow the same steps to define the missing information for the getMat method. In this example, getMat has an incomplete output argument, and you complete its definition by setting its size to the len argument.

methDef = clsDef.findMethod("getMat"); % Upon inspection, CPPOutput is incomplete.
methDef.CPPSignature % The length of output is defined by input argument len. 
argDef = methDef.CPPOutput;
argDef.define(Size="len");
methDef.Status
ans =
  DefinitionStatus enumeration
    Complete

Define copyMat Method

Follow the same steps to define the missing information for the copyMat method. In this example, copyMat has an incomplete input argument dest, and you complete its definition by setting its size to the len argument.

methDef = clsDef.findMethod("copyMat"); % Upon inspection, CPPInputs is incomplete.
methDef.CPPInputs % Upon inspection, the dest argument needs definition.
methDef.CPPSignature % The length of dest is defined by the input argument len.
argDef = methDef.CPPInputs([methDef.CPPInputs.Name] == "dest");
argDef.define(Size="len");
methDef.Status
ans =
  DefinitionStatus enumeration
    Complete

Define Incomplete Functions

Identify the incomplete functions.

idef.IncompleteFunctions
ans = 
  1×2 FunctionDefinition array with properties:

    CPPName
    MATLABName
    Overloaded
    CPPSignature
    MATLABSignature
    CPPInputs
    CPPOutput
    Status
    Included

  Display as table

Click the Display as table link to identify the incomplete functions:

         CPPName                       MATLABName                   Overloaded      Status      Included
    _________________    _______________________________________    __________    __________    ________

    "addMat"             "clib.matrix.addMat"                       false         Incomplete    false  
    "updateMatBySize"    "clib.matrix.updateMatBySize"              false         Incomplete    false  

Define addMat Function

Display the properties of the addMat function.

fcnDef = idef.findFunction("addMat")
fcnDef = 
  FunctionDefinition with properties:

            CPPName: "addMat"
         MATLABName: "clib.matrix.addMat"
         Overloaded: false
       CPPSignature: "int addMat(Mat const * mat)"
    MATLABSignature: <Define incomplete inputs to see the MATLAB signature.>
          CPPInputs: [1×1 clibgen.api.InputArgumentDefinition]
          CPPOutput: [1×1 clibgen.api.OutputArgumentDefinition]
             Status: Incomplete
           Included: false

  Show all properties

The MATLABSignature property shows that you must define incomplete inputs to see the MATLAB signature. Inspect the inputs.

fcnDef.CPPInputs
ans = 
  InputArgumentDefinition with properties:

          Name: "mat"
      Position: 1
       CPPType: "Mat const *"
    MATLABType: "clib.matrix.Mat"
     Direction: input
          Size: <undefined>
        Status: Incomplete

Display the signature to see how the function uses the mat argument.

fcnDef.CPPSignature
ans = "int addMat(Mat const * mat)"

Because mat is declared as a pointer, MATLAB cannot determine whether it points to a single object or an array. The function signature shows that only one Mat object is passed. Because the function takes a single argument, define its Size value as 1. Then verify that the addMat function is completely defined.

argDef = fcnDef.CPPInputs([fcnDef.CPPInputs.Name] == "mat");
argDef.define(Size=1);
fcnDef
fcnDef = 
  FunctionDefinition with properties:

            CPPName: "addMat"
         MATLABName: "clib.matrix.addMat"
         Overloaded: false
       CPPSignature: "int addMat(Mat const * mat)"
    MATLABSignature: RetVal = clib.matrix.addMat(mat)
          CPPInputs: [1×1 clibgen.api.InputArgumentDefinition]
          CPPOutput: [1×1 clibgen.api.OutputArgumentDefinition]
             Status: Complete
           Included: true

  Show all properties

Define updateMatBySize Function

Follow the same steps to define the missing information for the updateMatBySize function. In this example, updateMatBySize has an incomplete input argument arr, and you complete its definition by setting its size to the len argument.

fcnDef = idef.findFunction("updateMatBySize"); % Upon inspection, CPPInputs is incomplete.
fcnDef.CPPInputs % Upon inspection, the argument arr needs definition.
fcnDef.CPPSignature % The length of arr is defined by the input argument len.
argDef = fcnDef.CPPInputs([fcnDef.CPPInputs.Name] == "arr");
argDef.define(Size="len");
fcnDef
fcnDef = 
  FunctionDefinition with properties:

            CPPName: "updateMatBySize"
         MATLABName: "clib.matrix.updateMatBySize"
         Overloaded: false
       CPPSignature: "void updateMatBySize(Mat & mat,int * arr,size_t len)"
    MATLABSignature: clib.matrix.updateMatBySize(mat, arr)
          CPPInputs: [1×3 clibgen.api.InputArgumentDefinition]
          CPPOutput: [1×0 clibgen.api.OutputArgumentDefinition]
             Status: Complete
           Included: true

  Show all properties

Build Interface

With the class and function definitions complete, build the MATLAB interface to the C++ library by using the InterfaceDefinition build function. The build function creates the interface file in the folder specified by the OutputFolder property of the interface definition. In this example, the resulting interface file is matrixInterface.dll.

build(idef)

Add the interface file folder to the MATLAB path.

interfacePath = fullfile(idef.OutputFolder,idef.InterfaceName);
addpath(interfacePath)

Save Workflow Script

To reuse this workflow, save the commands from this example in a MATLAB script, such as publishmatrix.m. Running the script lets you regenerate the MATLAB interface after updating the C++ library and provides a starting point for adding customizations or automating interface generation as part of a CI workflow.

% Publish MATLAB Interface to C++ matrixOperations Library
% Create Interface Configuration
startpath = fullfile(matlabroot,"extern","examples","cpp_interface");
icfg = clibgen.api.InterfaceConfiguration("matrix");
icfg.HeaderFiles = fullfile(startpath,"matrixOperations.hpp");

% Create Interface Definition
idef = clibgen.api.InterfaceDefinition(icfg);
idef.SourceFiles = fullfile(startpath,"matrixOperations.cpp");
if ispc
  idef.Libraries = fullfile(startpath,"win64","mingw64","matrixOperations.lib");
elseif ismac
  idef.Libraries = fullfile(startpath,"maca64","matrixOperations.dylib");
elseif isunix
  idef.Libraries = fullfile(startpath,"glnxa64","matrixOperations.so");
end

% Define Incomplete Methods in Mat class
clsDef = idef.findClass("Mat");

methDef = clsDef.findMethod("setMat");
argDef = methDef.CPPInputs([methDef.CPPInputs.Name] == "src");
argDef.define(Size="len");

methDef = clsDef.findMethod("getMat");
argDef = methDef.CPPOutput;
argDef.define(Size="len");

methDef = clsDef.findMethod("copyMat");
argDef = methDef.CPPInputs([methDef.CPPInputs.Name] == "dest");
argDef.define(Size="len");

% Define Incomplete Functions
fcnDef = idef.findFunction("addMat");
argDef = fcnDef.CPPInputs([fcnDef.CPPInputs.Name] == "mat");
argDef.define(Size=1);

fcnDef = idef.findFunction("updateMatBySize");
argDef = fcnDef.CPPInputs([fcnDef.CPPInputs.Name] == "arr");
argDef.define(Size="len");

% Build Interface
build(idef)
interfacePath = fullfile(idef.OutputFolder,idef.InterfaceName);
addpath(interfacePath)

Test Interface

To test the MATLAB interface to the C++ library, enable out-of-process execution mode and run your test code.

Enable Out-of-Process Execution Mode

Before testing, run this command to call the interface library out of process. Out-of-process mode enables you to make changes to the interface definition object and rebuild the interface without having to restart MATLAB. For more information, see Load C/C++ Library In-Process or Out-of-Process.

libraryconfig = clibConfiguration("matrix",ExecutionMode="outofprocess")

Write Test Code

Write code to call and test the interface library.

matObj = clib.matrix.Mat;   % Create a Mat object
intArr = [1,2,3,4,5];
matObj.setMat(intArr);     % Set the values to intArr
retMat = matObj.getMat(5);
int32(retMat) % Display the values
ans = 1×5 int32 row vector
1	2	3	4	5

Share Interface

To share the interface with another MATLAB user, create a package installation file (.mltbx) by using the instructions in Distribute MATLAB Interface to C/C++ Library. For this example, you can share the matrix interface by following these steps:

  1. On the MATLAB Home tab, in the Environment section, select Add-Ons > Build Package.

  2. Set the package folder to your matrix folder, which contains the interface file matrixInterface.dll.

  3. When writing the package description, identify the namespace (calling syntax) as clib.matrix.

  4. Click Build Package. You can then share the package installation file with other MATLAB users.

See Also

Objects

Functions

Topics