Py_RunString仅返回无对象

时间:2015-05-26 06:03:56

标签: python c++

我正在使用嵌入在我的c ++项目中的Python 3.4.3,当我调用Py_RunString时,它总是返回None对象。 这是我的代码

#include <Python.h>
#include <string>
int main(){
    //Initialize the python interpreter
    Py_Initialize(); 
    //create new dictionary containing both global and local definitions
    PyObject *globals = PyDict_New();
    PyObject *locals = PyDict_New(); 

    //Set the build in definitions to the global dictionary: eg:len, str ,.. funtions
    PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
    //evaluate some python code and get the result, here is my issue, always None 
    PyObject *string_result = PyRun_StringFlags(
        "1 + 1" /*or what ever python code*/
        ,
        Py_file_input, globals, locals, NULL);
    //check whether the python code caused any Exception and print it
    if (PyErr_Occurred()) {
        PyErr_Print(); PyErr_Clear(); return 1;
    }
    else {
    //if no Exceptions then try To Get string represiation of the python object, But it always None
        auto str = PyToStr(string_result);
        printf("python result is %s",str);
    }
    return 0;
}

这是我的函数,它将任何python对象转换为c ++ std :: wstring

std::wstring PyToStr(PyObject*  Object)
{
    //it is equivalent to python code : str(Object)
    PyObject* objectsRepresentation = PyObject_Str(Object);
    //convert Python String Object to C++ wchar_t*
    const wchar_t* ws = PyUnicode_AsUnicode(objectsRepresentation);

    if (ws)
        return ws;
    //if ws is NULL it could not be converted implicitly to std::wstring
    return L"";
}

1 个答案:

答案 0 :(得分:0)

如果只想评估一行,则可以使用Py_eval_input代替Py_file_input。然后应返回评估值。