简体   繁体   English

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

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

I have in C++ a class TInt which contains an integer value and provides some methods on it. 我在C ++中有一个TInt类,其中包含一个整数值,并提供一些方法。 It also has a default constructor that accepts int which allows me in c++ to say: 它还有一个接受int的默认构造函数,它允许我在c ++中说:

TInt X=3;

I would like to export this and other classes to C# using SWIG and I'm not being able to figure out what do I need to do to be able to write in C# the same line: 我想使用SWIG将此类和其他类导出到C#,我无法弄清楚我需要做什么才能在C#中写入同一行:

TInt X=3;

Right now I'm getting an expected error "Cannot implicitly convert 'int' to 'TInt'" 目前,我收到预期的错误“无法将'int'隐式转换为'TInt'”

The thing is more complicated since there are also methods in other classes that accept TInt as an argument. 事情变得更加复杂,因为其他类中也有一些方法接受TInt作为参数。 For example, TIntV is a class containing a vector of TInt and has a method Add(TInt& Val). 例如,TIntV是包含TInt向量的类,并且具有方法Add(TInt&Val)。 In C# I can only call this method as: 在C#中,我只能将此方法称为:

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

Any help would be greatly appreciated. 任何帮助将不胜感激。

Gregor 格雷戈尔

I've found a complete solution that includes the answer by Xi Huan: 我找到了一个完整的解决方案,其中包括Xi Huan的答案:

In the SWIG's interface file (*.i) I've added the following lines: 在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);
    }
%}

this adds the operator to the generated .cs file. 这会将运算符添加到生成的.cs文件中。 One thing to keep in mind (that took me an hour to fix it) is that this content has to be in the interface file declared before the code that imports the c++ classes. 要记住的一件事(花了我一个小时来修复它)是这个内容必须在导入c ++类的代码之前声明的接口文件中。

You can the implicit keyword to declare an implicit user-defined type conversion operator. 您可以使用隐式关键字来声明隐式用户定义的类型转换运算符。

Example : 示例

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