Archive for August, 2011

You have your mixed mode assembly with a class that holds a pointer to the unmanaged class.

Option 1, old school:

System::Collections::Generic::List^ ClassManaged::GetValues()
{
     // get unmanaged values
     std::vector values = mpUnmanagedClass->getValues();

     array^ managedValues = gcnew array(values.size());

     // pin address of managed class (not moved by clr,
     // managed objects can have their references moved around on the heap)
     pin_ptr dest = &managedValues[0];

     // copy data to managed array
     std::memcpy(dest, &values[0], values.size()*sizeof(double));

     return gcnew List(managedValues);
}

Option 2, take advantage of interopservices.

System::Collections::Generic::List^ DoubleIndexM::GetIndexValues()
{
     // get unmanaged values
     std::vector values = mpUnmanagedClass->getValues();

     array^ managedValues = gcnew array(values.size());

     // cast to managed object type IntPtr representing an object pointer.
     System::IntPtr ptr = (System::IntPtr)&values[0];

     // copy data to managed array using System::Runtime::Interopservices namespace
     Marshal::Copy(ptr, managedValues, 0, values.size());

     return gcnew List(managedValues);
}

Posted By:
calc August 17, 2011