Click to See Complete Forum and Search --> : Arrays from C# to VB6


JKeenan
February 11th, 2005, 08:32 AM
if I create an array in a C# class, and I have a method in the class like

public void ReferenceArray(out short[] VB6ArrayRef)
{
VB6ArrayRef = mDefinedArray;
}

now on the VB6 side:

Dim Temp() As Integer
Dim Temp2() As Integer

mzSomeObject.ReferenceArray Temp
mzSomeObject.ReferenceArray Temp2
Temp(1) = 23

why does Temp2 not show the change that temp just made. The intent was for Temp and Temp to reference the same array which resides in the C# class.

checksal
February 13th, 2005, 12:05 AM
Why dont you try this:

public void ReferenceArray(ref short[] VB6ArrayRef)
{
VB6ArrayRef = mDefinedArray;
}

and pass in the array that you would like to reference mDefinedArray. I think this should work.

darwen
February 13th, 2005, 03:44 PM
The reason why it doesn't work is that you're expecting to get access to the pointer to the block of memory containing the .NET array.

You don't get this. In fact you should never get this : because the memory is managed it can change location at any time therefore if you could gain access to this pointer then it'd not be safe to assume it won't change.

What interop does is to COPY the array i.e. it creates an intermediate copy of the array which it passes back to VB6.

Therefore when you call ReferenceArray twice you're getting two copies of the array.

In fact .NET is conforming to good practice for DLLs. DLLs should NEVER pass pointers to internal memory back to clients. They should either copy the memory into some form of app-boundary safe memory (global or CoTaskMem type memory) and pass this back or get client to allocate the memory itself first and then copy the contents of its memory into that.

I hope this is clear.

Darwen.