c++调用python接口函数的传参问题
问题描述:C++调用python,遇到可选参数,不知道如何传参引起的问题
起初,网上搜到的都是用PyEval_CallObject ,但该接口不能传可选参数,
但在昨天,与chatgpt聊天中,它帮我解决了这个问题。现记录一下。
PyEval_CallObject 和 PyObject_Call
PyObject_Call函数原型
PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable_object,
PyObject *args, PyObject *kw);
PyEval_CallObject 函数原型
/* Inline this */
#define PyEval_CallObject(func,arg) \
PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
明显可以看出 PyEval_CallObject 接口,不支持可选参数。
PyEval_CallObject 的声明处,既ceval.h头文件中可看到
PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords(
PyObject *, PyObject *, PyObject *);
从上数可以,PyEval_CallObjectWithKeywords 支持可选参数的调用
ChatGPT给出的答案是使用PyObject_Call,根据实际情况,稍加修改后,示例代码如下:
要调用的python函数接口定义如下:
gdal2tiles.py
def generate_tiles(input_file,output_folder,**options)
pass
#include <Python.h>
int main(int argc, char *argv[])
{
// Initialize Python interpreter
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("import os");
PyRun_SimpleString("import string");
PyRun_SimpleString("sys.path.append('/usr/bin')");
// Import the module containing the function
PyObject *pModule = PyImport_ImportModule("gdal2tiles"); //py的名称
// Get a reference to the function
PyObject *pFunc = PyObject_GetAttrString(pModule, "generate_tiles"); //py中要调用的函数接口
// Create the arguments for the function
PyObject *pArgs = PyTuple_New(2); // Two arguments: input_file and out_folder
// Create the first argument: input_file
PyTuple_SetItem(pArgs, 0, Py_BuildValue("s","/home/map2d/share_data/hp.tif"));
// Create the second argument: out_folder
PyTuple_SetItem(pArgs, 1, Py_BuildValue("s","/home/map2d/share_data/hp_raster"));
// Create the keyword arguments for the function
PyObject *pOptions = PyDict_New();
PyDict_SetItemString(pOptions, "verbose", Py_False); // Set a boolean option
// Call the function with the arguments and keyword arguments
PyObject_Call(pFunc, pArgs, pOptions);
// Clean up
Py_DECREF(pModule);
Py_DECREF(pFunc);
Py_DECREF(pArgs);
Py_DECREF(pOptions);
// Shut down Python interpreter
Py_Finalize();
}