SWIG Python和C:参数 [英] SWIG with python and C: arguments

查看:139
本文介绍了SWIG Python和C:参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

void func(int* a, int b);

这我想在蟒蛇可以像这样:

Which I want to make available in python like so:

func(list, int)

即,用户通过列表和一个整数(告诉多少项应该被存储在列表中的功能)。要做到这一点,我需要知道在初始化为AB的值(因为我需要一个原始的C的int数组暂时)。

ie, the user passes a list and an integer (telling the functions how many entries should be stored in the list). To do this, I need to know the value of "b" in the initialization for "a" (because I need a raw C int array temporarily).

%typemap(in) ( int* a) {

//need to allocate sizeof(int) * b bytes temporarily

 }

但我不知道B的价值,因为它只是在后来解析!

But I don't know the value of "b" because it is only parsed later!

我怎样才能访问B参数的值?

How can I access the value of the "b" argument?

推荐答案

您可以使用多参数类型映射。

You can use a multi-argument typemap.

%typemap(in) (const int *a, int b) %{
    $2 = (int)PyList_Size($input);
    $1 = new int[$2];
    for(Py_ssize_t i = 0; i < $2; ++i)
        $1[i] = PyLong_AsLong(PyList_GET_ITEM($input,i));
%}

%typemap(freearg) (const int* a, int b) %{
    delete [] $1;
%}

这是假设你是路过的列表(因此 const int的* )。因为Python列表知道它的大小,没有必要通过的大小为好。还注意到没有错误在上述的例子检查

This assumes you are passing in a list (hence the const int*). Since a Python list knows its size there is no need to pass the size as well. Also note there is no error checking in the above example.

有了这个,你传递一个Python对象($输入)两个参数。 B ($ 2)的大小和 A ($ 1)分配一个新的 INT初始化数组的大小。数组的元素被复制到该阵列

With this you pass one Python object ($input) for the two parameters. b ($2) is initialized with the size and a ($1) allocates a new int array of that size. The elements of the array are copied to this array.

freearg 类型映射为函数被调用后清理。

The freearg typemap provides the cleanup after the function is called.

您使用它是这样的:

func([1,2,3,4,5])

如果您想返回一个列表,下面可以用:

If you want to return a list, the following can be used:

%typemap(in) (int *a, int b) %{
    $2 = (int)PyLong_AsLong($input);
    $1 = new int[$2];
%}

%typemap(argout) (int *a, int b) (PyObject* tmp) %{
    tmp = PyList_New($2);
    for(Py_ssize_t i = 0; i < $2; ++i)
        PyList_SET_ITEM(tmp, i, PyLong_FromLong($1[i]));
    $result = SWIG_Python_AppendOutput($result, tmp);
%}

%typemap(freearg) (int* a, int b) %{
    delete [] $1;
%}

请注意非const 为int * A 。 Python不需要的列表作为输入参数,返回一个,所以输入类型映射只是期望的整数(为简洁起见检查删除错误)。该argout类型映射构建一个Python列表出来的价值回报,并将其追加到输出结果。

Note non-const int *a. Python doesn't need a list as an input parameter to return one, so the input typemap just expects an integer (error checking removed for brevity). The argout typemap builds a Python list out of the values return and appends them to the output result.

使用这样的:

func(5)     # returns for example [1,2,3,4,5]

如果 FUNC 有返回值将返回 [RETVAL,[1,2,3,4,5]

这篇关于SWIG Python和C:参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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