0

我是 tensorflow 的新手,并且在 c++ 中包含 python 代码,因此我会对以下奇怪行为的任何提示/评论表示赞赏:我有一个带有 headerfile 的 c++ 类 pythoninterface pythoninterface.h

#include <string>
#include <iostream>

class pythoninterface{
private:
    const char* file;
    const char* funct;
    const char* filepath;

public:
    pythoninterface();

    ~pythoninterface();

    void CallFunction();
};

源文件pythoninterface.cpp

#include <Python.h>
#include <string>
#include <sstream>
#include <vector>
#include "pythoninterface.h"

pythoninterface::pythoninterface(){

    file = "TensorflowIncludePy";
    funct = "myTestFunction";
    filepath = "/path/To/TensorflowIncludePy.py";
}

void pythoninterface::CallFunction(){

   PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *presult;

   // Initialize the Python Interpreter
   Py_Initialize();

   //Set in path where to find the custom python module other than the path where Python's system modules/packages are found.
   std::stringstream changepath;
   changepath << "import sys; sys.path.insert(0, '" << filepath << "')";
   const std::string tmp = changepath.str();
   filepath = tmp.c_str();
   PyRun_SimpleString (this->filepath);


   // Build the name object
   pName = PyString_FromString(this->file);

   // Load the module object
   pModule = PyImport_Import(pName);

   if(pModule != NULL) {
   // pDict is a borrowed reference
       pDict = PyModule_GetDict(pModule);


       // pFunc is also a borrowed reference
       pFunc = PyDict_GetItemString(pDict, this->funct);

       if (PyCallable_Check(pFunc))
       {
           pValue=Py_BuildValue("()");
           printf("pValue is empty!\n");
           PyErr_Print();
           presult=PyObject_CallObject(pFunc,pValue);
           PyErr_Print();
       } else
       {
           PyErr_Print();
       }
       printf("Result is %d!\n",PyInt_AsLong(presult));
       Py_DECREF(pValue);

       // Clean up
       Py_DECREF(pModule);
       Py_DECREF(pName);
   }
   else{
       std::cout << "Python retuned null pointer, no file!" << std::endl;
   }

   // Finish the Python Interpreter
   Py_Finalize();
}

以及应该包含该函数的 Python 文件(TensorflowIncludePy.py):

def myTestFunction():
    print 'I am a function without an input!'
    gettingStartedTF()
    return 42


def gettingStartedTF():
    import tensorflow as tf #At this point the error occurs!
    hello = tf.constant('Hello, TensorFlow!')
    sess = tf.Session()
    print(sess.run(hello))
    return 42

最后在我的 main 函数中,我只创建一个pythoninterface对象p并调用该函数p.CallFunction()。c++ 和 python 代码之间的通信工作正常,但是当(在运行时)import tensorflow as tf到达该行时,我收到一条*** stack smashing detected ***错误消息并且程序完成。谁能猜出问题可能是什么或以前有过类似的问题?

我知道有一个 c++ tensorflow API,但我觉得在 python 中使用 tensorflow 更舒服,所以我认为这对我来说可能是完美的解决方案(显然它不是......:P)

4

0 回答 0