Search code examples
c#parametersmanaged-c++

Can a.NET variable length params method be called from Managed C++?


I have a method declared on an interface like so:

public interface IInterface
{
    void DoSomething(string format, params object[] arguments);
}

I am dynamically loading a managed c++ class that uses an implementation of this interface. The interface and inmplementation are both C#.

IInterface^ foo = gcnew Implentation();

This call is fine:

foo->DoSomething("string", someParam);

This call fails:

foo->DoSomething("string");

It looks like if there are no parameters to pass it just can't resolve the method which should accept any number of params (including zero of course). I could probably use a nullptr as a placeholder but that's pretty ugly or I could add a superfluous overload of DoSomething(string format) which isn't great either but better than making all calls more awkward than they should be.

Am I missing something or is this not supported? All the helpers on the internet show how to declare the params equivalent in c++ but that doesn't help in my scenario.


Solution

  • I can't replicate your problem.

    Given the C# interface & implementation:

    using System;
    
    namespace SomeNamespace
    {
        public interface IInterface
        {
            void Print(string format, params object[] args);
        }
    
        public class Implementation : IInterface
        {
            public void Print(string format, params object[] args)
            {
                Console.WriteLine(format, args);
            }
        }
    }
    

    This C++/CLI code works fine:

    using namespace System;
    using namespace SomeNamespace;
    
    public ref class Test
    {
    public:
        static void Run()
        {
            IInterface^ foo = gcnew Implementation();
            foo->Print("hello, {0}", "world");
            foo->Print("hello, world");
        }
    };
    

    Is there another element that is missing here? Or have I missed the point :)