Search code examples
c++octave

Can I describe a shared variable in multiple C++ functions that can be called in Octave?


Is it possible to keep a state variable that is shared by multiple C++ functions called by Octave? I tried to explain what I am doing below:

#include <iostream>
#include <octave/oct.h>
#include "stdlib.h"

int x = 0;

DEFUN_DLD(foo, args, , "foo"){
    x++;
    std::cout << "foo=" << x << "\n";
    octave_value_list retVal = ovl(x);
    return retVal;
}

DEFUN_DLD(bar, args, , "bar"){
    x++;
    std::cout << "bar=" << x << "\n";
    octave_value_list retVal = ovl(x);
    return retVal;
}

After I compiled the above .cpp file with mkoctfile, I am able to call them in Octave. My expectation from this code is incrementing the global variable x by 1 at every call of foo and bar. Apparently foo and bar functions recognizes x in different contexts. When I call foo and bar, both functions print 1 to the screen. Is there any way to define a common variable that can be reached by both functions?

By the way, I simplified the example by changing the type of x. I know that I can return it to Octave and feed both functions with the updated value of x. However, the type of x is actually a struct that I could not achieve to return to Octave.


Solution

  • Based on the information in the comments, you compiled like so:

    mkoctfile -c sandbox.cpp
    mkoctfile -o foo sandbox.o
    mkoctfile -o bar sandbox.o
    

    Instead you should be doing this:

    mkoctfile sandbox.cpp -o sandbox
    ln -s sandbox.oct foo.oct
    ln -s sandbox.oct bar.oct
    

    See the relevant page in the manual for more details: https://octave.org/doc/v6.1.0/Overloading-and-Autoloading.html#Overloading-and-Autoloading