c++调用python接口函数的传参问题

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();
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

囧囧乐途

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值