如何使用 boost/python 从 C++ 将 class 导入 .py 文件?

How do I import a class in a .py file from C++ using boost/python?

编辑:看起来我搞砸了第二个 post 的解决方案,但在我更正后它仍然给我一个错误。

编辑:我尝试使用完整路径导入,但它给了我一个相对导入错误。我又做了一个 post 关于它

目录如下所示:

project
   |__ utilities
   |      |__ foo.py
   |
   |__ boost_extensions
   |      |__ myclass.cpp
   |      |__ myclass.so
   |
   |__ someotherstuff
   |      |__ bar.py      
   |
   |__ __main__.py

从 bar.py 我可以像这样从 foo.py 导入一些东西:

from ..utilities.foo import Foo

但是,从 myclass.cpp 我不确定如何导入它。我试过了

boost::python::object mod = boost::python::import("..utilities.foo");

boost::python::object mod = boost::python::import("../utilities/foo.py");

都给我一个错误模块未找到错误:

ModuleNotFoundError: No module named '.'

我也看到了 并尝试了接受的答案,但它没有用(与以前相同的错误):

boost::python::object mod;
void set_global(){
    try{
        setenv("PYTHONPATH", ".", 1);
        Py_Initialize();
        mod = boost::python::import("..utilities.foo");
    }
}

我也尝试过使用 sysos 但是它仍然给我一个错误(来自对 this post 的回答):

    try{
        setenv("PYTHONPATH", ".", 1);
        Py_Initialize();
        boost::python::object sys = import("sys");
        boost::python::object os = import("os");
        // sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
        // os.path.dirname(__file__)
        boost::python::object arg1 = os.attr("path").attr("dirname")("__file__");
        // os.path.join(arg1, '..', 'Common')
        boost::python::object arg2 = os.attr("path").attr("join")(arg1, "..", "Common");
        // sys.path.append(arg2)
        sys.attr("path").attr("append")(arg2);
        mod = boost::python::import("..utilities.foo");
    } catch(int e){
        cout << "import failed" << endl;
    }

错误信息:

ModuleNotFoundError: No module named '.'

我该如何导入模块?

谢谢

我想出了一个解决方法:由于 Python 模块也是 PyObject,我可以在 Python 中加载模块并将其作为变量传递给 C++。这是代码:

C++ 文件:

boost::python::object mod;
void set_global(boost::python::object foo_module){
    mod = foo_module;
    // this is for testing
    boost::python::object test = mod.attr("Foo")(new A(1,1,1), NULL, 12);
    A* a = extract<A*>(test.attr("_A")) ;
    cout << a->_x << endl << a->_y << endl << a->_z << endl;
}

在python中(来自):

from .utilities import foo as foo_module
set_globals(foo_module)

输出:

1
1
1