将std::string传递给PyObject_CallFunction函数

4
当我运行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个回答

5

为了使您的代码正常工作,您应该向PyObject_CallFunction传递一个C风格字符串。要从std::string获取C字符串,请使用c_str()方法。因此,以下行:

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

应该长成这样:

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

我已经尝试过了,但是出现了错误:error: lvalue required as unary ‘&’ operand - Ben Hollier
糟糕,我错了,我不小心在 passedString.c_str() 前面使用了 & - Ben Hollier
是的,你需要传入一个char*,所以不需要使用& - Nasser Al-Shawwa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接