什么是“正确"?将布尔值传递给Python C扩展的方法? [英] What is the "correct" way to pass a boolean to a Python C extension?

查看:71
本文介绍了什么是“正确"?将布尔值传递给Python C扩展的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是python文档(http://docs.python.org/extending/extending.html)中的一个简单示例:

This is a simple example from the python documentation (http://docs.python.org/extending/extending.html):

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);
}

如果我想向该函数传递一个附加的布尔参数-做到这一点的正确"方法是什么?

If I want to pass an additional boolean parameter to the function - what's the "correct" way to do it?

似乎没有传递给PyArg_ParseTuple()的布尔选项.所以我想到了以下几点:

There doesn't seem to be a bool option to pass to PyArg_ParseTuple(). So I thought of the following:

  1. 读取一个整数并仅使用该值(因为bool是int的子类)
  2. 以整数调用PyBool_FromLong()
  3. 读取并反对,然后调用PyBool_Check()以确认它是布尔值
  4. 也许有一种方法可以获取任何类型的变量并获取其真值(即,空数组将是虚假的,等等),这是python函数通常执行的操作.

这些更可取吗?还有其他选择吗?

Any of these preferable? Other options?

推荐答案

4也许有一种方法可以获取任何类型的变量并获取其真值(即,空数组将是虚假的,等等),这就是python 功能通常可以做到.

4 maybe there's a way to get any type of variable and get its truth value (i.e an empty array will is falsy etc.) which is what python function usually do.

是:(来自 Python/C API参考)

int PyObject_IsTrue(PyObject *o)

如果对象o被认为是真实的,则返回1,否则返回0. 这等效于Python表达式not o.失败了 返回-1.

Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.

编辑.为了回答实际问题,我认为方法1是正确的,因为int确实是C中的对应类型.方法4很好,但是如果您将函数记录为bool,则您没有义务仅接受任何对象.在Python中,无缘无故地像3中那样进行显式类型检查.如2中那样转换为另一个Python对象对您的C代码没有帮助.

EDIT. To answer the actual question, I think approach 1 is correct, because int really is the corresponding type in C. Approach 4 is good, but if you document your function as taking a bool, you are not obligated to accept just any object. Explicit type checks as in 3 without a reason are frowned upon in Python. Conversion to another Python object as in 2 does not help your C code.

这篇关于什么是“正确"?将布尔值传递给Python C扩展的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆