c++ - MATLAB array conversion with clibgen

9 visualizaciones (últimos 30 días)
Boris
Boris el 9 de Dic. de 2022
Respondida: Divyanshu el 23 de Mzo. de 2023
Hello,
I am binding my c++ toolsets to MATLAB. The code is very Object Oriented so I cannot just use simple mex functions and have to use clibgen.
Ideally I'd only need 2 functions: one that convert 1D MATLAB array into c++ vectors, and another one converting c++ vectors to 1D MATLAB array. The first eventually work (with data copy, not references), but getting a vector out does not.
Here is a simple example, on Windows with minGW installed through MATLAB:
// c++ code in main.hpp file:
#include "MatlabDataArray.hpp"
// DUmmy function adding 5 to an array
matlab::data::Array add5(std::vector<double> foo)
{
std::vector<double> bar(foo);
for(auto &v:bar)
v+=5;
matlab::data::ArrayFactory fac;
return fac.createArray({bar.size()}, bar.begin(),bar.end());
}
// MATLAB side:
% getting the library path
library_files = [fullfile(matlabroot,"extern","lib","win64","mingw64","libMatlabDataArray.lib"),...
fullfile(matlabroot,"extern","lib","win64","mingw64","libMatlabEngine.lib")];
% generating headers
clibgen.generateLibraryDefinition("main.hpp",... % Headers
"OverwriteExistingDefinitionFiles",true, ...
"Libraries",library_files, ... % Uses the MATLAB libraries (.lib linked to MinGW)
PackageName="test"); % in clib, the package will be ingested as DAGGER
% compiling and adding to path
build(definetest);
addpath("test");
% Then generating MATLAB array
arr = zeros(1,5)+2;
% adding 5 to each elements
arr2 = clib.DAGGER.add5(arr);
% so far so good
% But the following line throw an error:
arr2 + arr
arr2 is not a MATLAB array and cannot be used in simple operation with other arrays, or figures, ...
I get errors like that...
Operator '+' is not supported for operands of type 'clib.test.matlab.data.Array'
The real questions are: Is there a way, on the c++ side to return MATLAB arrays usable in MATLAB (eventually without data copy)? and is there an easy way to convert it back from MATLAB (although it would add a LOT of code overhead)?
Thanks in advance,
B.

Respuestas (1)

Divyanshu
Divyanshu el 23 de Mzo. de 2023
According to the code snippet of main.hpp file, you are trying to create a MATLAB array using ArrayFactory and want to transfer it to the MATLAB workspace from C++ program.
You can go through the following documentation which explains in detail that how one can use the array created in C++ in the MATLAB workspace. Moreover, it has an example with code where an array is created in C++ and is then moved to the workspace of MATLAB and after certain calculations the result is fetched from MATLAB workspace and displayed in the C++ program.

Categorías

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

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by