Search code examples
c#c++swigswig-typemap

Swig: How to change the accessiblity of the generated C# classes from `public class` to `internal class`


I am using swig 4.0.x to wrap a c++ file.

Everything is working fine except I want to change the accessibility of the generated C# classes from public class to internal class.

So far what I have tried is this: In swig interface file

%module example

%{
    #include "include/exampleapi.h"
%}

%typemap(csclassmodifiers) SWIGTYPE "internal class"
%pragma(csharp) moduleclassmodifiers="internal class"

%include <windows.i>
%include "include/exampleapi.h"

The above code seems to work for the module class (example) and some other files. But it is not changing the accessibility modifier of all the generated classes.

Particularly, classes whose name starts with public class SWIGTYPE_xxx (probably known as proxy classes? These classes contain internal members and have a private member with type private global::System.Runtime.InteropServices.HandleRef) .

How do I make them internal class?


Solution

  • Okay, so I have figured it out after asking this question on swig github repository. Following answer courtesy to William Fulton:

    SWIGTYPE_xxx classes are called Type Wrapper Classes.

    You need to use the C type for the typemap that causes the type wrapper class to be generated. For example SWIGTYPE_p_int is wrapping an int *. Hence you'd use:

    %typemap(csclassmodifiers) int * "internal class"

    The defaults for all generated proxy and type wrapper classes comes from csharp.swg:

    %typemap(csclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE &&, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class"

    So just override these typemaps to provide your customised code and read the chapter on Typemaps in the documentation.