3
votes

Say I have an example.h file with following:

struct foo_bar {
  int x;
};

struct foo {
  struct {
    int y;
  } bar;
};

and example.i with following:

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

Now, when I generate the SWIG wrapper, SWIG defines a new struct foo_bar to access the nested bar struct in foo (also mentioned in the documentation). However this is causing foo_bar struct to be duplicated and it is failing the compilation.

So, how can I ask SWIG to use foo2 when SWIG creates custom structs to access nested structs of foo, so that all nested structs for foo are created like foo2_bar? I tried %rename but it only renames the wrapper functions, not the custom structs created by SWIG to access nested structs.

2

2 Answers

1
votes

You can use the advanced SWIG rename operator to selectively rename only nested classes, for example:

%rename("nestedprefix%s", %$isnested) "";

Will add 'nestedprefix' in front of the name of any nested type.

You could also use regex and fullname matching to convert struct foo { struct bar {};}; to foo_bar:

%rename("%(regex:/.*?(::)?([^:]*)(::)?([^:]+)/\\2_\\4/)s", %$isnested, fullname=1) "";

(The regex might need some tweaking to match all the weird cases I haven't thought of).

For the specific case you showed with the anonymous inner class you could do something like:

%module test

%rename("%s_inner", %$isnested, match$name="foo_bar") "";

%inline %{
struct foo_bar {};

struct foo {
  struct {
    int x;
  } bar;
};
%}

This renames just the nested class that would otherwise be called foo_bar, but not the original foo_bar.

Alternatively:

%rename("%s_inner", %$isnested, %$classname="foo") "";

Matches inner classes with the parent class named foo.

1
votes

For now, I'm doing a find throughout the C source code with /\bfoo\b/ and replace it with foo2.