Gregor Leban
Gregor Leban

Reputation: 552

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. It also has a default constructor that accepts int which allows me in c++ to say:

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:

TInt X=3;

Right now I'm getting an expected error "Cannot implicitly convert 'int' to 'TInt'"

The thing is more complicated since there are also methods in other classes that accept TInt as an argument. For example, TIntV is a class containing a vector of TInt and has a method Add(TInt& Val). In C# I can only call this method as:

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

Any help would be greatly appreciated.

Gregor

Upvotes: 2

Views: 934

Answers (2)

Gregor Leban
Gregor Leban

Reputation: 552

I've found a complete solution that includes the answer by Xi Huan:

In the SWIG's interface file (*.i) I've added the following lines:

%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. 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.

Upvotes: 4

sloth
sloth

Reputation: 101072

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

Upvotes: 3

Related Questions