使用 SWIG 将 C 结构体数组访问到 Python

2024-03-10

我尝试从 Python 调用现有的 C 代码。 C代码定义了一个结构体B包含一个结构体数组As。 C 代码还定义了一个函数,该函数在调用时将值放入结构中。我可以访问数组成员变量,但它不是列表(或支持索引的东西)。相反,我得到的是一个代理对象B*.

I found 这个问题 https://stackoverflow.com/q/5670456/210526,但看起来并没有完全解决。我也不知道如何创建 Python 类的实例B来替换PyString_FromString().

下面是演示我的问题以及如何执行它所需的代码:

例子.h

typedef struct A_s
{
  unsigned int thing;
  unsigned int other;
} A_t;

typedef struct B_s
{
  unsigned int size;
  A_t items[16];
} B_t;

unsigned int foo(B_t* b);

示例.c

#include "example.h"

unsigned int
foo(B_t* b)
{
  b->size = 1;
  b->items[0].thing = 1;
  b->items[0].other = 2;
}

例子.i

%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

%include "example.h"

setup.py

from distutils.core import setup, Extension

module1 = Extension('example', sources=['example.c', 'example.i'])
setup(name='Example', version='0.1', ext_modules=[module1])

script.py - 这使用库并演示失败。

import example
b = example.B_t()
example.foo(b)
print b.size
print b.items
for i in xrange(b.size):
    print b.items[i]

如何运行一切:

python setup.py build_ext --inplace
mv example.so _example.so
python script.py

你可以编写一些 C 辅助函数,例如:

int get_thing(B_t *this_b_t, int idx);
int get_other(B_t *this_b_t, int idx);
void set_thing(B_t *this_b_t, int idx, int val);
void set_other(B_t *this_b_t, int idx, int val);

包装它们,然后您可以使用从中获得的指针example.B_t()从数据结构安排中访问值,例如

>>> b = example.B_t()
>>> a_thing = example.get_thing(b, 0)
>>> example.set_thing(b,0,999)

希望这些 C 函数的实现应该是什么是显而易见的 - 如果不是我可以提供一个例子......

当然,这并不像能够像 python 列表一样访问 C 数组那么无缝 - 您可能可以使用类型映射来实现此目的,但我不记得在这种情况下需要的确切语法 - 您必须这样做SWIG 文档中的一些 RTFM

也可能在这里重复:使用 SWIG 在 python 中访问嵌套结构数组 https://stackoverflow.com/questions/7713318/nested-structure-array-access-in-python-using-swig?rq=1

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 SWIG 将 C 结构体数组访问到 Python 的相关文章

随机推荐