【问题标题】:Pass std::string into PyObject_CallFunction将 std::string 传递给 PyObject_CallFunction
【发布时间】:2015-09-26 03:31:22
【问题描述】:

当我运行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

【问题讨论】:

    标签: python c++ python-embedding


    【解决方案1】:

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

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

    应该是这样的:

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

    【讨论】:

    • 我试过了,我得到了错误:error: lvalue required as unary ‘&amp;’ operand
    • 糟糕,我错了,我不小心在passedString.c_str() 之前使用了&amp;
    • 是的,你需要传递char*,所以不需要&amp;
    猜你喜欢
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2011-07-17
    • 2011-04-18
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多