如何将对象强制转换为我不知道 C++/CLI 中类型参数的通用列表?



我正在编写MATLAB和c#之间的粘合代码(我无法访问MATLAB出售的代码)。

我想将List<T>映射到特定的MATLAB结构(结构数组)。在我的转换函数中有以下代码:

Object(实际上是List<MyClass>)转换为List<Object>会抛出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...
    }

转换为非泛型List类型有效:

auto olist = (System::Collections::IList^)o;

相关内容

  • 没有找到相关文章

最新更新