简体   繁体   English

在与 SWIG 接口后访问 C 中的嵌套结构 Python

[英]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:以下是两个标头的内容:

  1. "Sample.h" has: “Sample.h”有:
#include "Sample2.h"

typedef struct {
    int c;
    sJustFloats sJf;
}sTest;
  1. "Sample2.h" has: “Sample2.h”有:
typedef struct {
    float a;
    float b;
}sJustFloats;
  1. Sample.c just has: Sample.c 只有:
#include "Sample.h"
  1. My SWIG interface file has:我的 SWIG 接口文件有:
%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.
  1. Steps followed to get.so file that is imported in Python: Python导入的get.so文件步骤如下:
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:补充意见:

  • When I do 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'>
  • If I have both structs in the same file "Sample.h", I am able to access all the fields by doing:如果我在同一个文件“Sample.h”中有两个结构,我可以通过以下方式访问所有字段:
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM