How to compile Matlab class into C lib?

后端 未结 2 2055
遥遥无期
遥遥无期 2020-12-19 14:10

The origin of this question is from here How to use "global static" variable in matlab function called in c.

I\'m trying to encapsulate the \"global variab

2条回答
  •  甜味超标
    2020-12-19 14:59

    Following on from the thread in the previous post, the suggestion wasn't to wrap your functions in a class, but rather to use a class to pass about the global variable which compiling leaves you unable to use.

    classdef Foo < handle
      properties
        value
      end
    
      methods
        function obj = Foo(value)
          obj.value = value;
        end
      end
    end
    

    Note: the class Foo extends the handle class in order to make it pass by reference, rather than pass by value. See: the comparison between handle and value classes.

    function foo = matlabA()
      foo = new Foo(1);
    end
    
    function matlabB(foo)
      foo.value
    end
    

    As far as I know, the matlab compiler doesn't compile the code as such, but rather packages it with a copy of the MATLAB Component Runtime and writes some wrapper functions to handle invoking said runtime on the code from c/c++.

    I would recommend avoiding jumping back and forth between matlab and c/c++ too much; there is bound to be some overhead to converting the datatypes and invoking the MCR. All I really use it for is wrapping up a complex but self-contained matlab script (i.e.: doesn't need to interact with the c/c++ code mid way through said script) as a function, or packaging up code for deployment to environments which don't have a full copy of matlab.

    As an interesting side note: if you are calling C++ from within Matlab, and that C++ code needs access to a global variable, things are much easier. You can simply do this by wrapping your C++ code into a mexFunction and compiling that. In the places you need to access a variable which is in the Matlab workspace, you can do so using the mexGetVariablePtr which will return a read-only pointer to the data. The variable you are accessing can be in either the global workspace, or that of the function which called your mexFunction.

    With this approach I would suggest liberally comment the variable that you are getting in both the C++ and Matlab code, as the link between them may not be obvious from the Matlab side; you wouldn't want someone to come along later, edit the script and wonder why it had broken.

    In this case it seems that the C++ side doesn't really need access to the data, so you could refactor it to have matlab do the calling by wrapping the "get current position of fingers" code into a mexFunction, then have matlab do the loop:

    data = loadData();
    while(~stop) {
      position = getFingerPositionMex();
      soundByCoef(position, data);
    }
    

    Assuming you don't modify the data within soundByCoef Matlab will use pass by reference, so there will be no copying of the large dataset.

提交回复
热议问题