-1

I defined the function in C# DLL as follows,

public class Class1
{
    public static dynamic CS_Func()
    {
        dynamic obj = new ExpandoObject();
        obj.num = 99;
        return obj;
    }
}

In another C# EXE, it could be called like this:

public void CS_Caller()
{
    dynamic obj = Class1.CS_Func();
    int num = obj.num;  // OK
}

But if using C++/CLI, how should I call the CS_Func()?

void CPP_Caller()
{
    ExpandoObject ^obj = (ExpandoObject ^)Class1::CS_Func();
    //int num = obj->num;  // ERROR
}
lixiangc
  • 11
  • 2
  • 1
    Not an option, C++/CLI does not have the *binder* that's necessary to access the DLR. Write a little helper C# library instead. – Hans Passant May 05 '21 at 12:54

1 Answers1

0

It solved. Although C++/CLI does not have the keyword of dynamic, it can use ExpandoObject class, which belongs to .NET platform. And ExpandoObject implements the IEnumerable interface, which allows us to enumerate all properties of ExpandoObject.

using namespace System;
using namespace System::Dynamic;
using namespace System::Collections::Generic;  // NOT System::Collections

void Cpp_Caller()
{
    ExpandoObject ^obj = (ExpandoObject ^)Class1::CS_Func();    
    for each (KeyValuePair<String^, Object^> ^prop in obj)
    {
        String ^propname = prop->Key;
        Object ^propvalue = prop->Value;
        if (propname == "num")
        {
            int num = (int)propvalue;
        }
    }
}
lixiangc
  • 11
  • 2