【发布时间】:2022-01-13 00:08:03
【问题描述】:
首先,我对 C++ 编程和 pybind11 比较陌生。下面的例子应该能解释我的问题:
a.h:
namespace test {
class A {
public:
static int something;
};
void setSomething(int input);
}
a.cpp:
#include <pybind11/pybind11.h>
#include "a.h"
int test::A::something;
void test::setSomething(int input) {
A::something = input;
}
PYBIND11_MODULE(a, handle) {
handle.doc() = "I'm a docstring hehe";
handle.def("setSomething", &test::setSomething);
}
b.h:
namespace test {
class B {
public:
B();
int getSomething() const;
};
}
b.cpp:
#include <pybind11/pybind11.h>
#include "a.h"
#include "b.h"
namespace py = pybind11;
// int test::A::something;
test::B::B(){}
int test::B::getSomething() const {
return A::something;
}
PYBIND11_MODULE(b, handle) {
handle.doc() = "I'm a docstring hehe";
py::class_<test::B>(handle, "B")
.def(py::init())
.def("getSomething", &test::B::getSomething);
}
所以我有两个类 A 和 B,它们在 a.cpp 和 b.cpp 中定义,它们都有头文件 a.h 和 b.h。基本上,我正在尝试从 B 类中的 A 类访问静态变量。现在,如果我使用 CMake 编译它们并尝试运行 test.py 文件,我会得到一个 ImportError 告诉我 undefined symbol: _ZN4test1A9somethingE。我希望这不是一个愚蠢的问题。提前感谢您的帮助!
编辑:如果我在类中定义变量,它不会获取类之前或之后设置的值。
【问题讨论】: