[英]Accessing C nested structs in Python after interfacing with SWIG
Preface :前言:
I have two header files: "Sample.h" and "Sample2.h".我有两个 header 文件:“Sample.h”和“Sample2.h”。 Here are the contents of the two headers:
以下是两个标头的内容:
#include "Sample2.h"
typedef struct {
int c;
sJustFloats sJf;
}sTest;
typedef struct {
float a;
float b;
}sJustFloats;
#include "Sample.h"
%module Sample
%{
/* Put header files here or function declarations like below */
#include "Sample.h"
%}
%include "Sample.h"
%apply float {float a}; // For sJustFloats.a
%apply float {float b}; // For sJustFloats.b
%apply int {int c}; // For sTest.c
%apply sJustFloats {sJustFloats sJf}; // For sTest.sJf
%apply sTest {sTest test}; //I guess this exposes test struct itself.
gcc -c -fPIC Sample.c Sample_wrap.c -I /usr/include/python3.6m
ld -shared Sample.o Sample_wrap.o -o _Sample.so
Observations :观察:
I am able to import this as a module in Python and I can access fields of sTest as follows:我可以将其作为 Python 中的模块导入,并且可以按如下方式访问 sTest 的字段:
test = Sample.sTest()
test.c // To access "c" -- This works fine
Problem: I am not able to access fields of struct sJustFloats问题:我无法访问 struct sJustFloats的字段
If I do test.sJf()
, it gives me TypeError: 'SwigPyObject' object is not callable
.如果我执行
test.sJf()
,它会给我TypeError: 'SwigPyObject' object is not callable
。 Similarly test.sJf.a
gives: AttributeError: 'SwigPyObject' object has no attribute 'a'
同样
test.sJf.a
给出: AttributeError: 'SwigPyObject' object has no attribute 'a'
Can someone please tell me how to access members of the struct, sJustFloats?有人可以告诉我如何访问结构 sJustFloats 的成员吗?
Additional observations:补充意见:
type(Sample.sTest)
, it gives me <class 'type'>
, whereas doing type(Sample.sTest.sJf)
gives me <class 'property'>
.type(Sample.sTest)
时,它会给我<class 'type'>
,而执行type(Sample.sTest.sJf)
会给我<class 'property'>
。test = Sample.sTest()
sjf = test.sJf()
sjf.a # Works fine
sjf.b # Works fine
Am I missing something in the interface file?我在接口文件中遗漏了什么吗? Are there are nuances of SWIG that I'm unaware of?
是否有我不知道的 SWIG 细微差别?
SWIG doesn't recurse by default, but you need %include "Sample2.h"
after %include "Sample.h"
and don't need any of the %apply
:默认情况下,SWIG 不会递归,但您需要在
%include "Sample.h"
之后添加 % %include "Sample2.h"
" 并且不需要任何%apply
:
%module Sample
%{
#include "Sample.h"
%}
%include "Sample.h"
%include "Sample2.h"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.