导入时Pybind11嵌入式模块无法运行

问题描述

我正在浪费很多时间试图找出导入的模块无法正常工作的原因。

py_actor.cpp:

#include <pybind11/embed.h>
#include "py_actor.h"

namespace py = pybind11;

void Py_AddSpeed(double speed) 
{
    py_speed = speed;
}

PYBIND11_EMbedDED_MODULE(py_actor,m) {
    m.def("Py_AddSpeed",&Py_AddSpeed,"A function that adds speed to all actors");
}

test.py(在已编译的py_actor.cpython-38-x86_64-linux-gnu.so的同一文件夹中):

from py_actor import Py_AddSpeed

speed = 16.0
print('UPDATING SPEEED!')
Py_AddSpeed(speed)

主要位置:

py::scoped_interpreter guard{}; // start the interpreter and keep it alive
py::print("Hello,World! GZDoom Now runs Python :)"); // use the Python API

py::module test = py::module::import("test");

py :: print是否有效?是! “更新速度”有效吗? 不!为什么?我不知道。我已经将项目重新编译了大约一千次,并且导入的模块未“运行”。我什至尝试过:

py::exec(R"(
    import test
    print('Speeedd')
    print(test.speed)
)");

没有,没有导入错误,也没有结果。我在做什么错了?

解决方法

我已经发现问题出在哪里

py::module test = py::module::import("test");
py::print(test.attr("__file__"));

那时我意识到与某个内部模块存在冲突,因此我将该模块重命名为“ _test”,并且该模块可以正常工作。我希望这可以在将来拯救某人。