How do you return more than one variable when using the MATLAB interface to C++ libraries?

8 visualizaciones (últimos 30 días)
I am following the example in the following documentation link to get familiar with how to interface with C++ from MATLAB:
After following this example, I have the following question:
Is it possible to return multiple outputs from a C++ function that I am interfacing with?
Functions in C++ can only return one item so I am not sure if this is possible.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 10 de Nov. de 2021
Along with returning a value with the return statement, C++ function signatures can return an output by utilizing pointers as input. Please follow the steps below for an overview of the process of returning multiple outputs using the MATLAB interface to C++:
1. Create a file called "foo.hpp" with the following contents:
int foo(int *val) {
    *val = 1;
    return 0;
}
2. Execute the following command in the MATLAB Command Window:
>> clibgen.generateLibraryDefinition("foo.hpp")
3. Three files should be generated: "definefoo.mlx", "definefoo.m", and "fooData.xm"l. Open the file, "definefoo.mlx" in the MATLAB Live Editor.
4. Uncomment the code in the section called: "C++ function foo with MATLAB name clib.foo.foo" and replace <SHAPE> with "1". Add the following line of code to the section of code that you just uncommented:
defineArgument(fooDefinition, "val", "int32", "output", 1);
5. Build the definition file, "define.mlx", by executing the following command in the MATLAB Command Window:
>> build(definefoo)
This will create a new folder called "foo" which contains "fooInterface.dll" which will be used by "clib" to interface with the "foo" C++ library
6. Click on the "addpath" link that is generated after you finish building the "foo" package. You can also do this yourself by using the "addpath" command in the MATLAB Command Window with the following syntax"
>> addpath('<path to "foo" folder>')
Where <path to "foo" folder> is replaced with the path to the "foo" folder generated after completing step 5.
7. Execute the following function in the MATLAB Command Window to show that you can receive multiple outputs from the MATLAB interface to C++ libraries:
>> [out1, out2] = clib.foo.foo
out1 =
  int32
   0
out2 =
  int32
   1

Más respuestas (0)

Categorías

Más información sobre Build MATLAB Interface to C++ Library en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by