How to use “global static” variable in matlab function called in c

不打扰是莪最后的温柔 提交于 2020-01-02 04:41:10

问题


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();

回答1:


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


来源:https://stackoverflow.com/questions/15714825/how-to-use-global-static-variable-in-matlab-function-called-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!