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

Viewed 104

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.

3 Answers

You can place the static variable in a shared library and create two .oct files that are linked against the shared library:

x.h
//---------------
extern int x;


x.cc
//---------------
#include "x.h"
int x = 0;


foo.cc
//---------------
#include <iostream>
#include <octave/oct.h>
#include "stdlib.h"
#include "x.h"

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


bar.cc
//---------------
#include <iostream>
#include <octave/oct.h>
#include "stdlib.h"
#include "x.h"

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

On Windows it is sufficient that all files to be on the same directory and use this:

g++ -shared -o libx.dll x.cc

mkoctfile -lx foo.cc
mkoctfile -lx bar.cc

On Linux you need to add the directory that contains libx.so to LD_LIBRARY_PATH environment variable and use this:

g++ -shared -o libx.so x.cc

mkoctfile -lx foo.cc
mkoctfile -lx bar.cc

If one of the functions is cleared the shared variable remains on memory. It is cleared only when both functions are cleared.

Related