How to handle string arrays using swig and c #?

There is an init method in my C ++ class

int init(int argc, char **argv) 

I also have a callback,

 void callback(int num, char **str) 

My problem is that swig generates the weird SWIGTYPE_p_p_char.cs class, and not the string [] as expected. please advice.

+3
source share
1 answer

SWIG has several types for passing arrays to functions in arrays_csharp.i. However, for char *INPUT[] there is none, but we can adapt typemaps to accomplish what you want:

 %module test %include <arrays_csharp.i> CSHARP_ARRAYS(char *, string) %typemap(imtype, inattributes="[In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0, ArraySubType=UnmanagedType.LPStr)]") char *INPUT[] "string[]" %apply char *INPUT[] { char **argv } int foo(int argc, char **argv); 

This uses the SWIG CSHARP_ARRAYS macro to create typedefs for the string s array, but then replaces imtype, so we can provide our own marshaling information.

I think that should be enough. If you want, you can add overload to the generated module with:

 %pragma(csharp) modulecode = %{ public static int foo(string[] argv) { return foo(argv.Length, argv); } %} 

Note. Check this carefully - I have never written a C # program in my life (but I wrote a lot of SWIG + JNI). I found marshaling information on the MSDN forums , but did not check any of this except to verify that the output from SWIG looks reasonable. This is similar to this answer , with the addition of SizeParamIndex .

+2
source

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


All Articles