COM Interop and Array Pointers

M

Mike

I am using a COM DLL function that takes a pointer to the first
element in an array of short values.

Foo(short* array)

COM interop provides that function to me in the .NET world with a "ref
short" parameter.

Foo(ref short array)

It seems that no matter what I try, the function only sees the first
element in the array. Is there a way to get it to see then entire
array? Maybe by using some sort of marshalling I haven't tried yet?

Thanks,
Mike
 
E

Eusebiu

Hello...
If you write short* array is not actually... is a pointer to a memory zone
where is some information (it may be the start of an array).. so don't think
that this is an array... :)

To call that method correctly, you'll have to marshal the C# array to
unmanaged and send the size of the array.
So you'll have something like this...
//C++
void Foo(short* pArray, unsigned int size){...};

//C#
[DllImport("MyDll.dll")]
public static extern Foo(ref IntPtr arrayPointer, uint size);

To create arrayPointer you'll have to allocate some memory...
short[] myArray;
//init and set array elements

IntPtr arrayPointer = Marshal.AlloHGlobal(myArray.Length *
Marshal.SizeOf(typeof(short));

Marshal.Copy(myArray, 0, arrayPointer, myArray.Length);

//invoke method...
Foo(arrayPointer, myArray.Length);

Hope this helps...
 

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