c++ - 我可以在可以在 Octave 中调用的多个 C++ 函数中描述共享变量吗?

标签 c++ octave

是否可以保留由 Octave 调用的多个 C++ 函数共享的状态变量?我试图在下面解释我在做什么:

#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;
}

使用 mkoctfile 编译上述 .cpp 文件后,我可以在 Octave 中调用它们。我对这段代码的期望是在每次调用 foo 和 bar 时将全局变量 x 加 1。显然 foo 和 bar 函数在不同的上下文中识别 x。当我调用 foo 和 bar 时,这两个函数都将 1 打印到屏幕上。有没有办法定义两个函数都可以访问的公共(public)变量?

顺便说一句,我通过更改 x 的类型来简化示例。我知道我可以将其返回到 Octave 并为这两个函数提供 x 的更新值。然而,x的类型实际上是一个结构体,我无法实现返回Octave。

最佳答案

根据评论中的信息,您编译如下:

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

相反,你应该这样做:

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

有关更多详细信息,请参阅手册中的相关页面:https://octave.org/doc/v6.1.0/Overloading-and-Autoloading.html#Overloading-and-Autoloading

关于c++ - 我可以在可以在 Octave 中调用的多个 C++ 函数中描述共享变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66209587/

相关文章:

matlab - 错误: element number 2 undefined in return list

c++ - 从编译器获取参数时,有没有办法避免预处理器宏?

c++ - 如何从head tail和roll获取骨骼变换矩阵

c++ - 使用 strchr 重载 >>

linux - 替换数据文件中的值

python - 左矩阵除法和 Numpy Solve

matlab - Matlab 中的 DST 变换与 FFTW3

plot - 在 Windows 的 Octave 中打印绘图时有轴但没有线条

c++ - 将函数传递给类的 OO 方法

c++ - 如何在Qt Creator中制作.exe文件