How do I process string arrays with swig and C#?

只愿长相守 提交于 2019-12-23 15:27:38

问题


My C++ class has a method called init:

int init(int argc, char **argv)

Also, I have a callback:

void callback(int num, char **str)

My problem is that Swig generates a strange class SWIGTYPE_p_p_char.cs, and no string[] as I expected. Please, advice.


回答1:


SWIG has some typemaps for passing arrays to functions, in arrays_csharp.i. There isn't one for char *INPUT[] however but we can adapt the typemaps to do 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 macro CSHARP_ARRAYS to produce the typedefs for an array of strings, but then replaces the imtype so we can give our own marshaling information.

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

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

Note: Test this carefully - I've never written a C# program in my life (but have written lots of SWIG+JNI). I found the marshaling information on the MSDN forums but haven't tested any of this beyond checking that the output from SWIG looks sane. This seems to match this answer, with the addition of SizeParamIndex.



来源:https://stackoverflow.com/questions/12512549/how-do-i-process-string-arrays-with-swig-and-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!