PyBytes_AS_STRING意外输出

2024-10-03 15:35:09 发布

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

我试图用c++嵌入python。下面是用c++编写的代码。该代码应该返回“hello-unu-world”作为输出。但是PyBytes_AS_STRING没有返回“hello_world”。我使用的是python3.5版本,并尝试在visualstudio中编译代码。在

string myfunc(char * inp)
{
    Py_Initialize();
    PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue1;
    pName = PyUnicode_FromString("mod1");
    pModule = PyImport_Import(pName);
    pDict = PyModule_GetDict(pModule);
    pFunc = PyDict_GetItemString(pDict, "func1");
    pArgs = PyTuple_New(1);
    pValue1 = PyUnicode_FromString(inp);
    PyTuple_SetItem(pArgs, 0, pValue1);
    PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
    if (pResult == NULL)
        printf("Calling the python method failed.\n");
    string result = PyBytes_AS_STRING(pResult);
    cout << result << endl;
    Py_Finalize();
    return result;
}

int main()
{
    cout << myfunc("hello_world") << endl;
}

mod1.py:

^{pr2}$

Tags: 代码helloworldstringasresultpyobjectpdict