swig/python 联合中的结构数组
swig/python array of structure in a union
我是 swig/python 世界的初学者,试图访问 python 中的 C 结构数组,但出现以下错误:
TypeError: 'bar' object does not support indexing
这是我正在尝试做的事情的简化版本:
foo.h:
#include <inttypes.h>
typedef struct bar {
uint8_t val;
}bar;
typedef struct foo {
union {
bar b[2];
} u;
}foo;
int fill_foo(foo *);
foo.c:
#include "foo.h"
int
fill_foo(foo *var)
{
var->u.b[0].val = 10;
var->u.b[1].val = 20;
return 0;
}
foo_test.i:
%module foo_test
%{
#include "foo.h"
%}
%include "foo.h"
foo.py:
import foo_test
f = foo_test.foo()
foo_test.fill_foo(f)
print f.u.b[0]
我已经阅读了一些关于 c 数组和 swig 的其他帖子,但我不清楚如何解决这个特殊情况。如果有人能帮助我,我会很高兴。
经过一番摸索,我发现我需要扩展 struct bar 来解决这个问题。我能够使上面的示例代码与 foo_test.i 的以下添加一起使用。
%extend bar {
const bar __getitem__(int i) {
return $self[i];
}
}
缺点是我需要为每个用作数组的结构添加这样的扩展。仍然没有想出如何为所有结构数组解决这个问题。
我是 swig/python 世界的初学者,试图访问 python 中的 C 结构数组,但出现以下错误:
TypeError: 'bar' object does not support indexing
这是我正在尝试做的事情的简化版本:
foo.h:
#include <inttypes.h>
typedef struct bar {
uint8_t val;
}bar;
typedef struct foo {
union {
bar b[2];
} u;
}foo;
int fill_foo(foo *);
foo.c:
#include "foo.h"
int
fill_foo(foo *var)
{
var->u.b[0].val = 10;
var->u.b[1].val = 20;
return 0;
}
foo_test.i:
%module foo_test
%{
#include "foo.h"
%}
%include "foo.h"
foo.py:
import foo_test
f = foo_test.foo()
foo_test.fill_foo(f)
print f.u.b[0]
我已经阅读了一些关于 c 数组和 swig 的其他帖子,但我不清楚如何解决这个特殊情况。如果有人能帮助我,我会很高兴。
经过一番摸索,我发现我需要扩展 struct bar 来解决这个问题。我能够使上面的示例代码与 foo_test.i 的以下添加一起使用。
%extend bar {
const bar __getitem__(int i) {
return $self[i];
}
}
缺点是我需要为每个用作数组的结构添加这样的扩展。仍然没有想出如何为所有结构数组解决这个问题。