c++ - matlab c shared library: capturing matlab function output with mxArray*/mxArray** -
i trying call matlab function c code, trying follow whatever can on web. using matlab version r2014a running on ubuntu 14.04. lets function testfun.m
looks below --
function c = testfun(a, b) disp('doing testfun()'); c = + b ; disp('done testfun()'); end
now invoked mcc
make c-wrapper --
user@pc:/tmp/test$ mcc -b csharedlib:libtestfun testfun.m -v
then have libtestfun.c
, libtestfun.h
, libtestfun.so
files , create c file calls testfun()
--
#include <stdio.h> #include "libtestfun.h" int main() { libtestfuninitialize(); mxarray *a, *b, **c; double *x ; = mxcreatedoublescalar(4); x = mxgetpr(a); printf("a = %.1f\n", x[0]); b = mxcreatedoublescalar(5); x = mxgetpr(b); printf("b = %.1f\n", x[0]); *c = mxcreatedoublematrix(1, 1, mxreal); mlftestfun(1, c, a, b); x = mxgetpr(c[0]); printf("c = %.1f\n", x[0]); libtestfunterminate(); return 1 ; }
and building executable --
user@pc:/tmp/test$ mbuild test.c libtestfun.c -l.libtestfun.so -v
the fact signature function reads
lib_libtestfun_c_api bool mw_call_conv mlftestfun(int nargout, mxarray** c, mxarray* a, mxarray* b);
if notice, can see output c
declared mxarray**
, therefore using mxarray **c
in test.c
file.
but when run executable, see 0.0
value of c
, supposed 9.0
--
user@pc:/tmp/test$ ./test = 4.0 b = 5.0 c = 0.0
what going on?
why output declared mxarray**
in function signature? why can't see outputs produced disp()
function in testfun.m
?
any appreciated.
you have declared c
incorrectly. should mxarray*
. double pointer in signature because output. when write *c
de-referencing uninitialized pointer.
you need following code:
#include <stdio.h> #include "libtestfun.h" int main() { libtestfuninitialize(); mxarray *a; mxarray *b; mxarray *c = null; // output arg must initialized null double *x ; = mxcreatedoublescalar(4); x = mxgetpr(a); printf("a = %.1f\n", x[0]); b = mxcreatedoublescalar(5); x = mxgetpr(b); printf("b = %.1f\n", x[0]); if (mlftestfun(1, &c, a, b)) { x = mxgetpr(c); printf("c = %.1f\n", x[0]); } libtestfunterminate(); return 1 ; }
Comments
Post a Comment