使用Shiboken生成C++库的Python绑定

0 投票
1 回答
1039 浏览
提问于 2025-04-28 07:21

我按照维基上的教程 http://qt-project.org/wiki/PySide_Binding_Generation_Tutorial 操作,但在我的MacOSX上却无法正常工作。

到目前为止,我做了以下事情:

  • 构建了 FooLib(静态库)---> 生成了 libFooLib.a
  • 创建了 typesystem_foo.xml 文件
  • 用以下命令运行 shiboken:

    shiboken-2.7 global.h --include-paths=.:/opt/local/include/PySide-2.7:/opt/local/include --typesystem-paths=/opt/local/share/PySide-2.7/typesystems --output-directory=../FooLibBinding typesystem_foo.xml

  • 从生成的 C++ 代码构建 FooLibBinding 动态库 ---> 生成了 libFooLibBinding.dylib

现在,我没有直接从命令行运行 Python 解释器,而是写了一个 C++ 程序,这个程序会加载 Python 解释器并使用 FooLib 打开一个 .py 脚本。这个程序动态链接了 libFooLibBinding.dylib,所以我想所有需要的符号都应该在那儿;)

以下是代码:

#include <iostream>
#include <Python.h>

int main(int argc, char* argv[])
{

    ///Python init
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PySys_SetArgv(argc, argv); /// relative module import

    ///Try out loading the module, this is just for testing
    /// -----------
    PyObject *sysPath = PySys_GetObject("path");
    PyObject *path = PyString_FromString("/Users/alexandre/Downloads/BindingTest");
    int result = PyList_Insert(sysPath, 0, path);
    PyObject *pModule = PyImport_ImportModule("foolib");
    if (PyErr_Occurred())
            PyErr_Print();
    /// -----------

    ///Our python file to interpret
    const char* filename = "/Users/alexandre/Downloads/BindingTest/FooLibTest/foolib_test.py";
    FILE* file = fopen(filename,"r");
    PyRun_SimpleFile(file,filename);

    ///close python
    Py_Finalize();
    return 0;
}

运行这个程序时,第一次尝试加载模块时失败,提示: ImportError: No module named foolib

然后在运行 .py 脚本时又失败:

Traceback (most recent call last):
  File "/Users/alexandre/Downloads/BindingTest/FooLibTest/foolib_test.py", line 1, in <module>
    from foolib import FooClass
ImportError: No module named foolib

显然,它找不到从绑定生成的模块。我的问题是,我该怎么做才能让它找到这个模块呢?

教程中使用了 Makefile,但似乎除了链接动态库之外没有做太多其他的事情。

暂无标签

1 个回答

0

你的Shiboken命令行的包含路径里没有你foo.h文件的路径。我不能确定这是不是你问题的原因,但如果我也这样做的话,就不会生成以下文件:

  • math_wrapper.cpp
  • math_wrapper.h

...而这些文件显然是你需要的,用来编译foo库里的Maths类的支持。

撰写回答