bugzpodder
asked on
an array of pointers to a managed class
I am having trouble declaring an array of pointers to a managed class. I am REQUIRED to make all my codes managed.
I think my problem is best explained by some code:
namespace ns{
public __gc class node{ ... }; //this is the class i want the array of pointers to point to
public __gc class X{ //I want to use the array of pointers in this clas
node *ptrArray[]; //if i put a constant value in there, the compiler complains
//if i leave it like this it doesnt complain but what do i do with it??
};
}
please help me with this problem
I think my problem is best explained by some code:
namespace ns{
public __gc class node{ ... }; //this is the class i want the array of pointers to point to
public __gc class X{ //I want to use the array of pointers in this clas
node *ptrArray[]; //if i put a constant value in there, the compiler complains
//if i leave it like this it doesnt complain but what do i do with it??
};
}
please help me with this problem
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
So how do we use a managed pointers in unmanaged code?
Fortunatly .NET was expecting this problem and came up with a solution. You have to use the gcroot class. The gcroot class keeps track of a managed class instance on the managed heap. It provides a handle which can be used in unmanaged code to work with the managed object.
Example :
#include "stdafx.h"
#include <gcroot.h>
#using <mscorlib.dll>
using namespace System;
using namespace System::Runtime::InteropSe
public __gc class MyClass
{
};
int _tmain()
{
// two methods to make an array of managed objects
// method #1 : make the array aware that it is pointing to managed types
// an array in a managed project is by default __gc[]
// so __gc was not needed in the line below
MyClass * MyArrayA __gc [] = {new MyClass()};
// method #2 : make the array aware that is is pointing to unmanaged types
// this method also works when you are trying to work with managed objects
// in unmanaged onces
gcroot <MyClass *> MyArrayB __nogc [] = {new MyClass()};
// concluding using managed objects in unmanaged objects :
// gcroot <MyClass *> MyObject = new MyClass();
return 0;
}