Py_RunString只返回None Obj

2024-06-25 06:41:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的c++项目中使用python3.4.3embded,当我调用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

^{pr2}$

Tags: andthe对象pynonestringincludecode