Problem converting managed array (C++) to C# array

D

Dick Swager

The following code is from a solution with a C++ project and a C# project.
The C++ project creates a managed array and the C# project tries to use it.
But I am having a 'System.ValueType[]' to 'System.Drawing.Point[]'
conversion problem in the C# project. How is this supposed to be done?

-------------------------------------------------------------------
C++ project files
-------------------------------------------------------------------

// File: ArrayFiller.h
//
// Language: C++ with managed extensions
//
// The class, ArrayOfPoints, manages an array of Point objects. Since
// System::Drawing::point is a managed class, it cannot be stored in a
// native array so the managed array must be used.

#pragma once

using namespace System;
using namespace System::Drawing; // Point

namespace ArrayFiller
{
public ref class ArrayOfPoints
{
// This class maintains an array of Points. Since Point is
// a managed type it cannot be contained in a native array, so a
// managed array must be used.
array <Point^>^ arrayOfPoints;
int nSize;

public:
ArrayOfPoints ()
{
// Create a managed array to store Point objects
nSize = 20;
arrayOfPoints = gcnew array <Point^> (nSize);

// Populate the array with some Point objects.
for (int i = 0; i < nSize; ++i)
{
arrayOfPoints = gcnew Point (10 * i, 10 * i + 1);
}
}
property array <Point^>^ TheArray
{
array <Point^>^ get ()
{
return arrayOfPoints;
}
}
property int Size
{
int get ()
{
return nSize;
}
}
};

}

-------------------------------------------------------------------

// File: ArrayFiller.cpp
//
// This is the main DLL file.

#include "stdafx.h"

#include "ArrayFiller.h"

-------------------------------------------------------------------
C# project file
-------------------------------------------------------------------


// File: ArrayTest.cs
//
// Language: CSharp
//
// This file contains a class that attempts to use an array of Point
// objects that is maintained in a managed C++ project. The line
//
// points = filler.TheArray;
//
// fails with the error message:
// error CS0029: Cannot implicitly convert type 'System.ValueType[]' to
// 'System.Drawing.Point[]'

using System;
using System.Drawing;
using System.Collections.Generic;
using ArrayFiller;

namespace ConsoleApplicationArrayTest
{
class ArrayTestProgram
{
static void Main (string[] args)
{
ArrayOfPoints filler = new ArrayOfPoints ();
int nSize = filler.Size;
Point[] points = new Point[nSize];
//points = filler.TheArray;

for (int i = 0; i < nSize; ++i)
Console.WriteLine (points.ToString ());
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top