Add code to automatically generated class in SWIG

I am trying to find a way to add code to generated functions. I used typemaps to extend classes, but cannot find anything in the documentation on extending certain functions.

Given the following swig interface file:

%module Test %{ #include "example.h" %} %typemap(cscode) Example %{ bool 64bit = SizeOf(typeof(System.IntPtr)) == 8; static string Path = 64bit ? "/...Path to 64 bit dll.../" : "/...Path to 32 bit dll.../"; %} %include "example.h" 

I get the following C # code:

 public class MyClass : global::System.IDisposable { ... bool 64bit = SizeOf(typeof(System.IntPtr)) == 8; static string Path = 64bit ? "/...Path to 64 bit dll.../" : "/...Path to 32 bit dll.../"; ... public static SomeObject Process(...) { // Function defined in example.h <- I would like to add some code here. SomeObject ret = new SomeObject(...); } ... } 

I would like to add code to the Process function, this code calls the SetDllDirectory(Path) call, which loads the correct dll depending on the type of platform. This should happen inside a call to Process() .

Any help is much appreciated!

+5
source share
2 answers

You can create the code you are looking for using %typemap(csout) . This is a bit of a hack, and you will need to copy some existing sample maps for SWIGTYPE (which is the common owner of the place), which can be found in csharp.swg

So, for example, given the header file example.h:

 struct SomeObject {}; struct MyClass { static SomeObject test(); }; 

Then you can write the following SWIG interface file:

 %module Test %{ #include "example.h" %} %typemap(csout,excode=SWIGEXCODE) SomeObject { // Some extra stuff here $&csclassname ret = new $&csclassname($imcall, true);$excode return ret; } %include "example.h" 

What produces:

 public static SomeObject test() { // Some extra stuff here SomeObject ret = new SomeObject(TestPINVOKE.MyClass_test(), true); return ret; } 

If you want to generate this for all types of return values, and not just for the things that SomeObject returns, you will have a little more work for all csout options.

+3
source

Section 20.8.7 of the SWIG documents shows how to use typemap(cscode) to extend the generated classes.

-1
source

Source: https://habr.com/ru/post/1207046/


All Articles