Return dynamic object in C++/CLI to C#

c#, c++-cli, dynamic

Solution

You can create a dynamic object in c++/cli, you just can't consume it there as you would in C# project. However you can consume it from C#. Here is how you do it:

In C++/CLI create a property or a method that returns Object^. Mark this property or method with System::Runtime::CompilerServices::DynamicAttribute. You are good to go.

Here is a quick sample I created:

namespace ClassLibrary1 
{
    using namespace System;
    using namespace System::Dynamic;

    public ref class Class1 : public DynamicObject
    {
    public:
        [System::Runtime::CompilerServices::Dynamic]
        static property Object^ Global
        {
        public:
            Object^ get()
            {
                return gcnew Class1();
            }
        }

    public:
        String^ Test()
        {
            return "Test";
        }
    };
}

And my C# consumer:

Console.WriteLine( ClassLibrary1.Class1.Global.Test() );

Problem

I've got a C++/CLI project that wraps a large number of classes - and the classes have their own meta-data system. So I'd like to return a dynamic object to make some use cases easy in C#. But I don't see how to do this in C++. In C# I can write the following: ``` dynamic TestThisOut() { return null; } void mork() { var d = TestThisOut(); d.Fork(); } ``` I would like to write `TestThisOut()` in C++/CLI, so that I can use it exactly the same way as I do in the "mork" function above (i.e. not having to type the dynamic keyword). Is this possible?

Original source