《扩展和嵌入python解释器》1.7 在扩展函数中提取参数

本文详细介绍了Python C API中的PyArg_ParseTuple函数使用方法及示例。解析了如何通过此函数将Python参数转换为C语言的数据类型,并给出了多个具体的调用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.7 在扩展函数中提取参数

PyArg_ParseTuple() 函数声明如下:

 

int PyArg_ParseTuple(PyObject *arg, char *format, ...);

arg参数必须是元组对象,该元组包含从Python传递到C函数的参数列表。 format参数的格式必须是一个格式化的字符串, 格式化字符串的语法在"Parsing arguments and building values" 的Python/C API Reference Manual章节中解释,其他参数必须是变量地址,其类型有格式化字符串参数决定。

注意:当PyArg_ParseTuple()函数检查Python参数需要的类型时,不能检查调用传入C变量地址的有效性:如果你输入错误,你的代码也许崩溃,或者至少是改写了内存的随机地址。所以请小心!

注意任何提供给调用者的Python对象引用是borrowed引用,不增加引用计数。

一些调用例子:

 

    int ok;
    int i, j;
    long k, l;
    const char *s;
    int size;

    ok = PyArg_ParseTuple(args, ""); /* No arguments */
        /* Python call: f() */
 
    ok = PyArg_ParseTuple(args, "s", &s); /* A string */
        /* Possible Python call: f('whoops!') */
 
    ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
        /* Possible Python call: f(1, 2, 'three') */
 
    ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
        /* A pair of ints and a string, whose size is also returned */
        /* Possible Python call: f((1, 2), 'three') */
 
    {
        const char *file;
        const char *mode = "r";
        int bufsize = 0;
        ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
        /* A string, and optionally another string and an integer */
        /* Possible Python calls:
           f('spam')
           f('spam', 'w')
           f('spam', 'wb', 100000) */
    }
 
    {
        int left, top, right, bottom, h, v;
        ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
                 &left, &top, &right, &bottom, &h, &v);
        /* A rectangle and a point */
        /* Possible Python call:
           f(((0, 0), (400, 300)), (10, 10)) */
    }
 
    {
        Py_complex c;
        ok = PyArg_ParseTuple(args, "D:myfunction", &c);
        /* a complex, also providing a function name for errors */
        /* Possible Python call: myfunction(1+2j) */
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值