stack smashing调用python函数导入tensorflow c ++

时间:2017-08-15 13:04:31

标签: c++ python-2.7 tensorflow stack-smash

我是新的tensorflow以及在c ++中包含python代码,因此我会对以下奇怪的行为提出任何提示/评论: 我有一个带有头文件pythoninterface.h的c ++类python接口:

#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)

0 个答案:

没有答案