Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "global static" variable in matlab function called in c

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();
like image 374
SolessChong Avatar asked Nov 03 '22 01:11

SolessChong


1 Answers

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
like image 158
Amro Avatar answered Nov 15 '22 05:11

Amro