5

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!

MATLAB

function matlabA()
    global foo
    foo = 1;
end

function matlabB()
    global foo
    foo
end

C++

cppA();
cppB();
Amro
  • 123,847
  • 25
  • 243
  • 454
SolessChong
  • 3,370
  • 8
  • 40
  • 67

1 Answers1

2

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:

FooData.m

classdef FooData < handle
    properties
        val
    end
end

fun_A.m

function foo = fun_A()
    foo = FooData();
    foo.val = 1;
end

fun_B.m

function fun_B(foo)
    disp(foo.val)
end
Amro
  • 123,847
  • 25
  • 243
  • 454
  • Thanks for your quick answer. Originally I thought it would be too obscure for anybody to answer. – SolessChong Mar 31 '13 at 15:53
  • @SolessCHong: welcome to SO! I hope the proposed solution worked for you? – Amro Mar 31 '13 at 23:00
  • The idea really helped and I think the code is sure to work. However the program is actually more confiscated than shown above and it's my part time project, so it will take me some time to reconstruct the matlab code. – SolessChong Apr 01 '13 at 14:46
  • Hi I'll be more than grateful if you could check out this new thread. http://stackoverflow.com/questions/15747411/how-to-compile-matlab-class-into-c-lib – SolessChong Apr 01 '13 at 16:39