简体   繁体   中英

Calling Matlab SDK function from C++

I created a C library using Matlab Compiler SDK, and am struggling to call the function in it.

The function definition in Matlab looks like this, so it has no arguments and returns one value of double(3)

function val = test6()
    val = double(3);
end

And the header file has this line.

extern LIB_libtest6_C_API bool MW_CALL_CONV mlfTest6(int nargout, mxArray** val);

So, my question is, how can I call this function in C++ and get the return value (double)3? I tried the one below, but what is printed is 1, not 3, so clearly something is wrong with this.

#include "libtest6.h"
int main(){
    mxArray** d;
    libtest6Initialize();
    std::cout << mlfTest6(1, d) <<std::endl;
    return 0;
}

Thanks in advance.

[I don't have the MATLAB Compiler, so cannot test any of this, excuse inaccuracies.]

The function's return value is a Boolean indicating whether the call was successful or not.

The function will output its result as an mxArray. The mxArray is allocated by the function and assigned into your pointer array, but you do need to allocate the pointer array:

mxArray* d[1];

After calling the function, you will have a mxArray in d[0] . Use theC Matrix API to access its contents:

  • mxIsDouble(d[0]) verifies that it's a double array.
  • Use mxGetDimensions(d[0]) to extract the sizes and verify it's not empty.
  • mxGetPr(d[0]) returns a pointer to the data in the array. In more recent versions of MATLAB, use mxGetDoubles instead.

So your minimal bit of code is

if(!mlfTest6(1, d)) {
    exit(1);
}
std::cout << *mxGetPr(d[0]) << '\n';

But I highly recommend to verify that the array you get back is how you expect it to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM