Passing an array from unmanaged C++ to C#

Viewed 281

I'm new to C++/CLI wrapper to C#, I've some issues on passing array to C#.

Native c++

const double *NDimInversion::GetOutputAverage() const
{
    if ( mOutputOk )
        return mAvgY.data().begin();
    else
        throw runtime_error("Error in NDimInversion::GetOutputAverage(): output not available.");
}

Native header

const double *GetOutputAverage() const;

Wrapper header

public ref class NDimInversion
public: 
  array<double>^ GetOutputAverage();

Wrapper c++

array<double>^ NDimInversion::GetOutputAverage() {

    array<double> tempArr = nDimInversion->GetOutputAverage(); // ???? 

    const int SIZE = tempArr.size();
    array<double>^ tempReturn = gcnew array<double>(SIZE);
    for (int i = 0; i < SIZE; i++)
    {
        tempReturn[i] = tempArr[i];
    }

    return tempReturn
};

I plan to convert the native return into CLI array, but I couldn't pass the array. Can you point me what am I missing?
Do I need to carry "const" keyword to CLI as well?

1 Answers

This describes how to copy between managed and unmanaged arrays. Example From this question:

System::Runtime::InteropServices::Marshal::Copy( IntPtr( ( void * ) sourcePointer), targetManagedArray, 0, dataSize ); 

As mentioned in the comments, you absolutely need to know the number of items in the source array.

Related