【问题标题】:failing to import a python module generated by swig into C++无法将 swig 生成的 python 模块导入 C++
【发布时间】:2015-12-21 23:46:48
【问题描述】:

我用 swig 生成了一个 Python 模块,它封装了一些 C++ 代码:

我的 .i 文件:

%module module_test

%{
#define SWIG_FILE_WITH_INIT
#include "headers.h"
%}

%include "headers.h"

我运行了这些命令:

swig -c++ -python swig.i

swig -Wall -c++ -python -external-runtime runtime_swig.h

构建后,这会生成一个 module_test.py 和一个 _module_test.pyd 文件。 包装器在 python 中工作正常。

现在,我正在尝试从另一个 C++ 项目加载这个新的 python 模块,使用以下代码:

 Py_Initialize();

  PySys_SetPath(L"path_to_my_files");
  PyObject * pName = PyString_FromString("module_test.py");

  PyObject *module = PyImport_Import(pName);

  if(module == NULL)
  {
     PyErr_Print();
    std::cout << "module == NULL !!";
    exit(-1);
  }

但是导入失败并出现错误:

 import imp
ImportError: No module named 'imp'

有人可以告诉我发生了什么事吗? swig 生成的 module_test.py 文件在代码中执行“import imp”,但是当我从 python 运行文件时,此导入从未失败... 我是否需要指定其他内容以便 C++ 代码知道“imp”是什么?

谢谢!

【问题讨论】:

    标签: python c++ swig


    【解决方案1】:

    通过使用解决它:

    PyObject *sys = PyImport_ImportModule("sys");
      PyObject *path = PyObject_GetAttrString(sys, "path");
      PyList_Append(path, PyString_FromString("path_to_file"));
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多