如何使用 swig 和 C# 处理字符串数组? [英] How do I process string arrays with swig and C#?

查看:35
本文介绍了如何使用 swig 和 C# 处理字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 C++ 类有一个名为 init 的方法:

My C++ class has a method called init:

int init(int argc, char **argv)

另外,我有一个回调:

void callback(int num, char **str)

我的问题是 Swig 生成了一个奇怪的类 SWIGTYPE_p_p_char.cs,并且没有我预期的 string[].请指教.

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

推荐答案

SWIG 在 arrays_csharp.i 中有一些用于将数组传递给函数的类型映射.char *INPUT[] 没有,但是我们可以调整类型图来做你想做的事:

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);

这使用 SWIG 宏 CSHARP_ARRAYS 为 string 数组生成 typedef,然后替换 imtype,以便我们可以提供我们自己的编组信息.

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);
  }
%}

注意:请仔细测试 - 我一生中从未编写过 C# 程序(但编写了大量 SWIG+JNI).我在 MSDN 上找到了 编组信息论坛,但除了检查 SWIG 的输出看起来正常之外,还没有测试过任何其他内容.这似乎与 this answer 相匹配,并添加了 SizeParamIndex.

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.

这篇关于如何使用 swig 和 C# 处理字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆