将 std::string 传递到 PyObject_CallFunction

Orf*_*fby 4 c++ python python-embedding

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

std::string passedString = "String";
pResult = PyObject_CallFunction(pFunc, "s", &passedString)
Run Code Online (Sandbox Code Playgroud)

然后将 pResult 转换为 a 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();
}
Run Code Online (Sandbox Code Playgroud)

Python 脚本(字符串.py):

def getString(returnString):
        return returnString
Run Code Online (Sandbox Code Playgroud)

我在 Ubuntu (linux) 上并且使用 Python 3.4

nas*_*-sh 5

您应该传递一个 C 风格的字符串才能PyObject_CallFunction使您的代码正常工作。为了从 a 获取 c 字符串std::string,请使用该c_str()方法。所以下面这一行:

pResult = PyObject_CallFunction(pFunc, "s", &passedString);
Run Code Online (Sandbox Code Playgroud)

应该看起来像这样:

pResult = PyObject_CallFunction(pFunc, "s", passedString.c_str());
Run Code Online (Sandbox Code Playgroud)