栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

SWIG / python数组内部结构

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SWIG / python数组内部结构

最简单的方法是将数组包装在内

struct
,然后可以提供额外的方法来满足“可订阅”的要求。

我整理了一个小例子。假定您使用的是C ++,但是从中构造等效的C版本相当简单,它只需要重复一些即可。

首先,具有

struct
要包装的C ++头文件和用于包装固定大小数组的模板:

template <typename Type, size_t N>struct wrapped_array {  Type data[N];};typedef struct {    wrapped_array<int, 40> icntl;    wrapped_array<double, 15> cntl;    int      *irn, *jcn;} Test;

我们相应的SWIG界面如下所示:

%module test%{#include "test.h"#include <exception>%}%include "test.h"%include "std_except.i"%extend wrapped_array {  inline size_t __len__() const { return N; }  inline const Type& __getitem__(size_t i) const throw(std::out_of_range) {    if (i >= N || i < 0)      throw std::out_of_range("out of bounds access");    return self->data[i];  }  inline void __setitem__(size_t i, const Type& v) throw(std::out_of_range) {    if (i >= N || i < 0)      throw std::out_of_range("out of bounds access");    self->data[i] = v;  }}%template (intArray40) wrapped_array<int, 40>;%template (doubleArray15) wrapped_array<double, 15>;

诀窍在于,我们曾经

%extend
提供过
__getitem__
Python用于下标读取和
__setitem__
写入的内容。(我们也可以提供一个
__iter__
使它可迭代的类型)。我们还给出了
wraped_array
要使用唯一名称的特定s,以使SWIG将它们包装在输出中。

使用提供的接口,我们现在可以执行以下操作:

>>> import test>>> foo = test.Test()>>> foo.icntl[30] = -654321>>> print foo.icntl[30]-654321>>> print foo.icntl[40]Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "test.py", line 108, in __getitem__    def __getitem__(self, *args): return _test.intArray40___getitem__(self, *args)IndexError: out of bounds access

您可能还会发现这种方法很有用/有趣,可以作为替代方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/571037.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号