Click to See Complete Forum and Search --> : Array of managed types as function parameter


tmccoy00
July 9th, 2007, 09:51 PM
I'm trying to allocate an array of managed structures inside a library, and return the allocated arrays back to the caller. I now realise this is a violation of scoping, and could do with some assistance to rectify this.

Library

public: ref struct Record
{
DateTime Timestamp;
Int32 Value;
};

public: myPublicLibraryFunction(array<Record^> ^Record);
...
int size = 50;
array<Record^> ^myArray = gcnew array<Record^>(size);
...
Record ^myRecord = gcnew Record^;
Record->Value = 5;
Record->Timestamp = DateTime::Now;
myArray->SetValue(Record, 0);

Library User

array<Record^> ^myUserArray;
...
myLibrary::myPublicLibraryFunction(myUserArray);

...but the end result is that the myUserArray appears to not be allocated when returning from the library call. Interestingly, when inside the library call, the array is allocated and available correctly - it appears to be suffering from garbage collection when the compiler thinks it's out of scope at the end of the myPublicLibraryFunction call.

This is showing holes in my understanding of Visual Studio 2005 memory allocation, but the short of what I want is to have pointers to arrays in the user code, have the arrays allocated inside the library and then accessible when returning to user code.

I can see why this is happening - it's a scope issue or similar, but am struggling to battle this.

darwen
July 10th, 2007, 03:58 AM
Firstly you can do this :


ref class MyClass
{
public:
array<Record ^> ^ GetArray()
{
return gcnew array<Record ^(10);
}
} ;


I.e. return the array. This is probably what you want.

What you're trying to do is to pass in a reference to a reference, or in C++/CLI it's called a tracking reference and is refferred to as the % operator :


ref class MyClass
{
public:
void MyFunction(array<Record ^> ^% result)
{
result = gcnew array<Record ^>(10);
}
} ;


This will have the desired effect. It's main use is when you want to return more than one parameter from the function. For a single result, you should return it.

Darwen.