Generate a SWIG interface for this struct.
(self)
| 216 | return definition |
| 217 | |
| 218 | def to_swig(self): |
| 219 | '''Generate a SWIG interface for this struct.''' |
| 220 | # luckily, swig treats all structs as pointers anyway |
| 221 | definition = 'typedef struct {0.c_name} {{}} {0.c_name};\n'.format(self) |
| 222 | # see: |
| 223 | # http://www.swig.org/Doc3.0/Arguments.html#Arguments_nn4 |
| 224 | # note: this prints "Can't apply (sp_Apple *INPUT). No typemaps are defined." |
| 225 | # but afaict that's a complete lie, it totally works |
| 226 | definition += '%apply {0.c_name}* INPUT {{ {0.c_name}* a }};'.format(self) |
| 227 | # We use SWIG's %extend command to attach "methods" to this struct: |
| 228 | # %extend Bananas { |
| 229 | # int peel(int); |
| 230 | # } |
| 231 | # results in a `peel` method on the Bananas object, which |
| 232 | # calls into a method: |
| 233 | # int Bananas_peel(Bananas *self, int) |
| 234 | # which we generate :) |
| 235 | |
| 236 | body = '' |
| 237 | if self.constructor_: |
| 238 | body += f'''{self.c_name}({", ".join(a.to_swig() for a in self.constructor_.args)});\n''' |
| 239 | |
| 240 | body += f'~{self.c_name}();\n' |
| 241 | for method in self.methods: |
| 242 | if not method.static: |
| 243 | body += method.to_swig() |
| 244 | for member in self.members: |
| 245 | body += f'\n{member.to_swig()};\n' |
| 246 | |
| 247 | body = s(body, indent=4) |
| 248 | extra = f'%extend {self.c_name} {{\n{body}}}' |
| 249 | |
| 250 | statics = '' |
| 251 | for method in self.methods: |
| 252 | if method.static: |
| 253 | statics += super(Method, method).to_swig() + '\n' |
| 254 | |
| 255 | return f'{definition}\n{extra}\n{statics}\n' |
| 256 | |
| 257 | def to_rust(self): |
| 258 | '''Generate a rust implementation for this struct.''' |