繁体   English   中英

C ++-> C#使用SWIG:如何为类使用默认构造函数

[英]C++ -> C# using SWIG: how to use default constructor for a class

我在C ++中有一个TInt类,其中包含一个整数值,并提供一些方法。 它还有一个接受int的默认构造函数,它允许我在c ++中说:

TInt X=3;

我想使用SWIG将此类和其他类导出到C#,我无法弄清楚我需要做什么才能在C#中写入同一行:

TInt X=3;

目前,我收到预期的错误“无法将'int'隐式转换为'TInt'”

事情变得更加复杂,因为其他类中也有一些方法接受TInt作为参数。 例如,TIntV是包含TInt向量的类,并且具有方法Add(TInt&Val)。 在C#中,我只能将此方法称为:

TIntV Arr;
Arr.Add(new TInt(3));

任何帮助将不胜感激。

格雷戈尔

我找到了一个完整的解决方案,其中包括Xi Huan的答案:

在SWIG的界面文件(* .i)中,我添加了以下行:

%typemap(cscode) TInt %{
    //this will be added to the generated wrapper for TInt class
    public static implicit operator TInt(int d)
    {
        return new TInt(d);
    }
%}

这会将运算符添加到生成的.cs文件中。 要记住的一件事(花了我一个小时来修复它)是这个内容必须在导入c ++类的代码之前声明的接口文件中。

您可以使用隐式关键字来声明隐式用户定义的类型转换运算符。

示例

public class Test
{
    public static void Main()
    {
        TInt X = 3;
        Console.WriteLine(X);
    }
}

class TInt
{
    public TInt(int d) { _intvalue = d; }
    public TInt() { }

    int _intvalue;

    public static implicit operator TInt(int d)
    {
        return new TInt(d);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM