I know how to call a function defined in an .m-file using the Octave interpreter and feval
as shown in the Octave manual but not how to do something similar using Octave classes and their methods.
If I have a simple class defined in Octave using the classdef method such as
classdef TestClass < handle
properties
val
endproperties
methods
function obj = TestClass()
obj.val = 1;
endfunction
function obj = setval(obj, v)
obj.val = v;
endfunction
function showval(obj)
disp(obj.val);
endfunction
endmethods
endclassdef
If I then would would like to use my class in some C++ code, how would I go about doing that. In Octave it would be:
c = TestClass(); //create an instance of TestClass
c.setval(100); //use the objects methods
c.showval(); //display 100
Based on the answer below I'll present my solution here. The above octave code can be rewritten as
c = TestClass();
setval(c, 100);
showval(c);
which can be turned into this C++ code
#include <interpreter.h>
#include <parse.h>
int main()
{
octave::interpreter interpreter;
interpreter.execute();
octave_value_list arg;
octave_value c;
c = octave::feval("TestClass", arg, 1).xelem(0);
arg(0) = c;
arg(1) = 100;
octave::feval("setval", arg);
arg.clear();
arg(0) = c;
octave::feval("showval", arg);
return 0;
}
If you already know how to call an Octave function from C++, then all you are missing is that a.b()
is the same as b(a)
. Calling a method is just like calling a function, there is no distinction. Octave figures out which overload of the function to call based on the input arguments.
The bit of Octave code you posted,
c = TestClass();
c.setval(100);
c.showval();
can also be written as
c = TestClass();
setval(c, 100);
showval(c);