将python代码嵌入C ++时进行多次导入

时间:2018-08-16 09:49:03

标签: python c++ tensorflow

现在我有一个C ++项目,该项目通过调用如下函数来导入python代码(受过训练的tensorflow网络):

void smt()
{
    PyObject* pModule = PyImport_ImportModule("apply_lstm");//seems to be problematic
    PyObject* pDict = PyModule_GetDict(pModule);
    PyObject* pFunHi = PyDict_GetItemString(pDict, "python_pred");
    double CArray[6 * 16 * 16] = { 0 };
    PyObject* PyList = PyList_New(6 * 16 * 16);
    PyObject* ArgList = PyTuple_New(1);
    for (Py_ssize_t Index_i = 0; Index_i < PyList_Size(PyList); Index_i++)
    {
        PyList_SetItem(PyList, Index_i, PyFloat_FromDouble(CArray[Index_i]));
    }
    PyTuple_SetItem(ArgList, 0, PyList);
    PyObject* pRes = PyObject_CallObject(pFunHi, ArgList);

    if (!pRes)cout << "python func. not called!" << endl;
    if (PyList_Check(pRes))
    {
        int SizeOfList = PyList_Size(pRes);
        for (Py_ssize_t Index_i = 0; Index_i < SizeOfList; Index_i++)
        {
            PyObject *Item = PyList_GetItem(pRes, Index_i);
            cout << PyFloat_AsDouble(Item) << " ";
            Py_DECREF(Item);
        }
    }

    Py_DECREF(pModule);
    Py_DECREF(pDict);
    Py_DECREF(pFunHi);
    Py_DECREF(PyList);
    Py_DECREF(ArgList);
    Py_DECREF(pRes);
}

Py_Initialize()和Py_Finalize()在此函数之外。此函数应被多次调用。第一次运行良好。第二次BUt程序崩溃,什么也不输出。看来问题出在多次导入(tensorflow模块)上。 python代码类似于:

import tensorflow as tf
import numpy as np
import os
from tensorflow.contrib import rnn

def python_pred(x_input):
    ...

我第二次使用print()进行验证的程序在第二次调用中没有任何一行。所以我不显示其余代码。如果有人可以为我解决此问题,我将不胜感激。

0 个答案:

没有答案