将std :: string传递给PyObject_CallFunction

时间:2015-07-08 09:44:36

标签: python c++ python-embedding

当我运行pResult = PyObject_CallFunction(pFunc, "s", &"String")时,python脚本返回正确的字符串。但是,如果我尝试运行这个:

std::string passedString = "String";
pResult = PyObject_CallFunction(pFunc, "s", &passedString)

然后将pResult转换为std::string,打印时我得到<NULL>。这是一些(可能)完整的代码,它返回<NULL>

C ++代码:

#include <Python.h>
#include <string>
#include <iostream>

int main()
{
    PyObject *pName, *pModule, *pDict, *pFunc;

    // Set PYTHONPATH TO working directory
    setenv("PYTHONPATH",".",1); //This doesn't help
    setenv("PYTHONDONTWRITEBYTECODE", " ", 1);

    // Initialize the Python Interpreter
    Py_Initialize();

    // Build the name object
    pName = PyUnicode_FromString((char*)"string");
    // Load the module object
    pModule = PyImport_Import(pName);
    // pDict is a borrowed reference
    pDict = PyModule_GetDict(pModule);
    // pFunc is also a borrowed reference
    pFunc = PyDict_GetItemString(pDict, (char*)"getString");

    if (pFunc != NULL)
    {
        if (PyCallable_Check(pFunc))
        {
            PyObject *pResult;

            std::string passedString = "String";
            pResult = PyObject_CallFunction(pFunc, "s", &passedString);

            PyObject* pResultStr = PyObject_Repr(pResult);

            std::string returnedString = PyUnicode_AsUTF8(pResultStr);
            std::cout << returnedString << std::endl;

            Py_DECREF(pResult);
            Py_DECREF(pResultStr);
        }
        else {PyErr_Print();}
    }
    else {std::cout << "pFunc is NULL!" << std::endl;}

    // Clean up
    Py_DECREF(pFunc);
    Py_DECREF(pDict);
    Py_DECREF(pModule);
    Py_DECREF(pName);

    // Finish the Python Interpreter
    Py_Finalize();
}

Python脚本(string.py):

def getString(returnString):
        return returnString

我在Ubuntu(linux)上,我使用的是Python 3.4

1 个答案:

答案 0 :(得分:2)

您应该将c样式字符串传递给PyObject_CallFunction,以使代码生效。要从std::string获取c字符串,请使用c_str()方法。所以以下一行:

pResult = PyObject_CallFunction(pFunc, "s", &passedString);

应该是这样的:

pResult = PyObject_CallFunction(pFunc, "s", passedString.c_str());