C# SWIG vector <string> 到 string[]

标签 c# c++ swig

给定 C++ 方法,例如

std::vector< std::string > getFoo();
void setFoo( const std::vector< std::string > &foo);

如何让 SWIG 将其公开给 C#

string[] getFoo();
setFoo(string[] foo);

我意识到很多 people have asked关于vector<string>和 SWIG,但我还没有看到任何解决与 string[] 之间的转换的问题。每个人都提到使用 SWIG 模板,就像这样

%template(StringVector) vector<string>;

但这只是创建了一个数据类型,调用者必须知道该数据类型才能手动编码(marshal)。理想情况下,调用者只需处理 string[]并让 SWIG 层来解决它。

我怎样才能简单地使用 string[]在 C# 中,但将其变成 vector<string>在 C++ 中?

最佳答案

一种方法可能是添加 implicit casting到 SWIG 生成的 StringVector,以便它能够将自身转换为 string[]

我尝试通过 typemap 执行此操作,但无法使其工作。但是,可以通过partial classes来完成。 .

它看起来像这样。在 SWIG 中,

%include std_vector.i
%include std_string.i

/* allow partial c# classes */
%typemap(csclassmodifiers) SWIGTYPE "public partial class"

/* generate template around vector<string> */
%template(StringVector) std::vector< std::string >;

然后在 C# 中,创建 StringVector 的部分版本:

public partial class StringVector: IDisposable, System.Collections.IEnumerable
#if !SWIG_DOTNET_1
    , System.Collections.Generic.IList<string>
#endif
{
    // cast from C# string array
    public static implicit operator StringVector(string[] inVal) {
        var outVal= new StringVector();
        foreach (string element in inVal) {
            outVal.Add(element);
        }
        return outVal;
    }

    // cast to C# string array
    public static implicit operator string[](StringVector inVal) {
        var outVal= new string[inVal.Count];
        inVal.CopyTo(outVal);
        return outVal;
    }
}

这允许您编写如下所示的 C# 代码:

string[] foo= mymodule.getFoo();
string[] thenewfoo= { "one", "two", "three" };
mymodule.setFoo(thenewfoo);

它仍然是 C# 方法签名中的 StringVector,但由于客户端编码器可以只使用 string[],所以这并不重要。

关于C# SWIG vector <string> 到 string[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147026/

相关文章:

c# - system.reflection 问题,GetFields 不返回所有内容

c++ - 命名空间定义和异常(exception)

python - swig 忽略继承的函数

python - 为 C 库创建 Python 绑定(bind)的 SWIG 问题

java - Swig:将返回类型 std::string 转换为 java byte[]

c# - 有什么好的方法可以找到应用程序中的瓶颈吗?

c# - 如何从Xml作为对象而不是字符串检索值?

c# - 延迟验证

c++ - 为什么要使用 'extern "C+ +"' ?

c++ - 记忆化和朴素算法 - 2 个不同的答案