Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call overloaded c# functions which the only difference is parameter passed by ref or not in c++/cli

I've a C# class library with overloaded methods, and one method has a ref parameter and the other has a value parameter. I can call these methods in C#, but I can't get it right in C++/CLI. It's seems compiler can't distinguish these two methods.

Here is my C# code

namespace test {
    public class test {
        public static void foo(int i)
        {
            i++;
        }
        public static void foo(ref int i)
        {
            i++;
        }
    }
}

and my C++/CLI code

int main(array<System::String ^> ^args)
{
    int i=0;
    test::test::foo(i);     //error C2668: ambiguous call to overloaded function
    test::test::foo(%i);    //error C3071: operator '%' can only be applied to an instance of a ref class or a value-type
    int %r=i;
    test::test::foo(r);     //error C2668: ambiguous call to overloaded function
    Console::WriteLine(i);
    return 0;
}

I know in C++ I can't declare overload functions where the only difference in the function signature is that one takes an object and another takes reference to an object, but in C# I can.

Is this a feature supported in C# but not in C++/CLI? Is there any workaround?

like image 650
czz Avatar asked Jul 03 '12 08:07

czz


People also ask

How do you call an overloaded function?

The function call operator () can be overloaded for objects of class type. When you overload ( ), you are not creating a new way to call a function. Rather, you are creating an operator function that can be passed an arbitrary number of parameters.

What is overloaded in C?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java.

Does C have overloaded operators?

C does not support operator overloading (beyond what it built into the language).

Can * be overloaded in C++?

C++ adds a few of its own operators, most of which can be overloaded except :: and . * .


1 Answers

As a workaround you could build a C# helper class that you use in C++/CLI

namespace test
{
    public class testHelper
    {
        public static void fooByVal(int i)
        {
            test.foo(i);
        }

        public static void fooByRef(ref int i)
        {
            test.foo(ref i);
        }
    }
}
like image 163
Sebastian Negraszus Avatar answered Nov 15 '22 20:11

Sebastian Negraszus