Hi I'm currently coding in MATLAB and C. I have compiled MATLAB functions into a C shared library using MATLAB Compiler (mcc), and called the functions in the shared library in a C++ program.
Can a global variable be declared to share data between MATLAB functions when called in C++?
To be exact, if there is a function matlabA()
and function matlabB()
in matlab, and is compiled into c++ shared library using mcc compiler as cppA()
and cppB()
, can I share a variable between them just by declaring variables as global in matlabA()
and matlabB()
?
It doesn't appear to work, then how can I share variable between functions?
Thanks!
function matlabA()
global foo
foo = 1;
end
function matlabB()
global foo
foo
end
cppA();
cppB();
According to this blog post by Loren Shure, it is strongly recommended not to use non-constant static variables (e.g. read/write globals) in deployed applications.
Instead you can create a handle class to encapsulate the data, and explicitly pass the object to those functions (which has reference copy semantics).
Example:
classdef FooData < handle
properties
val
end
end
function foo = fun_A()
foo = FooData();
foo.val = 1;
end
function fun_B(foo)
disp(foo.val)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With