gpt4 book ai didi

python - SWIG 与 python 和 C : arguments

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:49 25 4
gpt4 key购买 nike

我有这个功能:

void func(int* a, int b);

我想像这样在 python 中提供:

func(list, int)

即,用户传递一个列表和一个整数(告诉函数应该在列表中存储多少条目)。为此,我需要在“a”的初始化中知道“b”的值(因为我暂时需要一个原始的 C int 数组)。

%typemap(in) ( int* a) {

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

}

但是我不知道“b”的值,因为它只是在后面解析的!

如何访问“b”参数的值?

最佳答案

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

%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;
%}

这假设您要传递 in 列表(因此 const int*)。由于 Python 列表知道它的大小,因此也不需要传递大小。另请注意,上面的示例中没有错误检查。

通过这种方式,您可以为两个参数传递一个 Python 对象($input)。 b ($2) 用大小初始化,a ($1) 分配一个新的 int 数组。数组的元素被复制到这个数组。

freearg 类型映射提供函数调用后的清理。

你可以这样使用它:

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

如果你想返回一个列表,可以使用如下:

%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;
%}

注意非常量 int *a。 Python 不需要列表作为输入参数来返回一个,因此输入类型映射只需要一个整数(为简洁起见删除了错误检查)。 argout 类型映射根据返回值构建一个 Python 列表,并将它们附加到输出结果。

像这样使用它:

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

如果 func 有返回值,它将返回 [retval, [1,2,3,4,5]]

关于python - SWIG 与 python 和 C : arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23015860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com