c ++中的嵌入式python代码 - 导入python库时出错

时间:2017-09-12 06:44:33

标签: python c++ python-c-api python-embedding

我正在尝试使用嵌入在C ++程序中的Python 3.5解释器从C ++接收图像,并将其用作我训练的张量流模型的输入。首先,我将我的图像转换为numpy数组,然后将其发送到python。这是我的简化代码,工作正常(代码来自here):

Python代码:

def multiply_fun(M):
    V = M*2
    print(V)

调用上述函数的我的C ++代码:

#include <Python.h>
#include <abstract.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <ndarrayobject.h>
#include <vector>


int main()
{
    Py_InitializeEx(1);

    PyObject* sysPath = PySys_GetObject((char*)"path");
    PyObject* curDir = PyUnicode_FromString(".");
    PyList_Append(sysPath, curDir);
    Py_DECREF(curDir);

    PyObject* python_code = PyImport_ImportModule("python_code");
    PyObject* multiply_fun = PyObject_GetAttrString(python_code, "multiply_fun");
    Py_XDECREF(python_code);

    import_array1(-1);
    npy_intp dim[] = { 5, 5 };
    std::vector<double> buffer(5*5, 1);

    PyObject* array_2d = PyArray_SimpleNewFromData(2, dim, NPY_DOUBLE, &buffer[0]);
    PyObject* return_value1 = PyObject_CallFunction(multiply_fun, "O", array_2d);

    Py_XDECREF(return_value1);
    Py_XDECREF(array_2d);
    Py_XDECREF(multiply_fun);

    Py_Finalize();
    return 0;
} 

但是,当我想使用大多数python库时,我收到一个错误。例如,对于这个python代码:

def multiply_fun(M):
    from skimage.io import imsave
    imsave('test.png', M)

我收到了这个错误:

Exception ignored in: <module 'threading' from 'C:\\Users\\Matin\\Anaconda3\\Lib\\threading.py'>
Traceback (most recent call last):
  File "C:\Users\Matin\Anaconda3\Lib\threading.py", line 1283, in _shutdown
    assert tlock.locked()
SystemError: <built-in method locked of _thread.lock object at 0x0000000002AF4418> returned a result with an error set

顺便说一句,This related discussion无法帮助我。

感谢您的帮助。

编辑1: 通过将from skimage.io import imsave移动到python函数之外(如注释中建议的@moooeeeep),我在此行中得到Null:

PyObject* python_code = PyImport_ImportModule("python_code");

1 个答案:

答案 0 :(得分:1)

似乎问题是PyImport_ImportModule在使用from package.submodule import function时无法加载某些包的子模块。已在Python/C API Reference Manual中解释:

  

当name参数包含一个点(当它指定一个子模块时)   一个包),fromlist参数设置为列表[&#39; *&#39;]这样   返回值是指定的模块而不是顶级包   包含它,否则将是这种情况。 (不幸的是,这有   当name实际上指定一个子包时,会产生额外的副作用   而不是子模块:包中指定的子模块   加载所有变量。)返回对导入模块的新引用,或者在失败时设置异常的NULL。失败的导入   模块不会将模块保留在sys.modules中。

     

此功能始终使用绝对导入。