我有以下问题。我想通过Python / C API将此python api嵌入到我的C ++程序中。
如何将参数传递传递给下面的函数?特别是,我如何处理这种特殊的 python **** wargs ?
?__init__
(用户名,密码,**)参数:
关键字参数:
根据我到目前为止所读的内容,这对于前两个参数是正确的:
#include <Python.h>
#include <iostream>
int main()
{
// Initialize the Python interpreter.
Py_Initialize();
// Create some Python objects that will later be assigned values.
PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
// Convert the file name to a Python string.
pName = PyUnicode_FromString("Sample");
// Import the file as a Python module.
pModule = PyImport_Import(pName);
// Create a dictionary for the contents of the module.
pDict = PyModule_GetDict(pModule);
// Get the add method from the dictionary.
pFunc = PyDict_GetItemString(pDict, "__init__");
// Create a Python tuple to hold the arguments to the method.
pArgs = PyTuple_New(2);
// make arguments
PyObject *pValue1 = PyUnicode_FromString("IGusername");
PyObject *pValue2 = PyUnicode_FromString("IGpassword");
// Set the Python strings as the first and second arguments to the method.
PyTuple_SetItem(pArgs, 0, pValue);
PyTuple_SetItem(pArgs, 1, pValue);
// Call the function with the arguments.
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
// Print a message if calling the method failed.
if (pResult == NULL)
printf("Calling the add method failed.\n");
// Convert the result to a long from a Python object.
//#########how to get the returned string##############
long result = XXXXXXXXXXXXX(pResult);
// Destroy the Python interpreter.
Py_Finalize();
// Print the result.
printf("The result is %d.\n", result);
std::cin.ignore();
return 0;
}
如果它是字符串,我如何获得返回值?
这是一个整数:
long result = PyLong_AsLong(pResult);