mardi 26 mai 2015

How can I cast an Object to a generic List I don't know the type parameter of in C++/CLR?

I'm writing glue code between MATLAB and C# (I don't have access to the one sold by MATLAB).

I want to map List to a particular MATLAB structure (array of structs). In my conversion function the code below.

Casting an Object (which is actually a List) to a List throws an InvalidCastException.

    // o is an C# Object I want to convert
    System::Type^ t = o->GetType();
    System::Type^ GenericListType = System::Collections::Generic::List<int>::typeid->GetGenericTypeDefinition();
    System::Type^ gt = t->IsGenericType ? t->GetGenericTypeDefinition() : nullptr;

    // ...

    // List<T> check
    else if (gt == GenericListType) {
        // map List<struct/class> to matlab struct array (export public fields only)
        // using actual matrix (dims != 1x1)
        // this save space as the fields name are stored only once

        // I can't cast to an explictit List<T> because T can be any class
        // but I need to know the list size

        // XXX: throws InvalidCastExceptions
        auto olist = (System::Collections::Generic::List<System::Object^>^)o; 
        const int count = olist->Count;

        if (count == 0) {
            System::Console::WriteLine("from_c_to_ml(): empty List<T>, returning nullptr, crash probably imminent, farewell my friends...");
            return nullptr;
        }

        // Now we need the actual type T (of List<T>) to know the public fields
        auto tlist = olist[0]->GetType();
        array<System::Reflection::FieldInfo^>^ fields = tlist->GetFields();
        const int fieldnb = fields->Length;

        // do stuff with it...
    }





Aucun commentaire:

Enregistrer un commentaire