4

I need to create a SafeArray to pass to a COM method.
How do I create/maintain/destroy a SafeArray in C#?

I have never came across SafeArrays before and could not find much with a quick google search, so any help is much appreciated.

EDIT: Added Sample Code:

The COM method signature

[id(0x000000d5)]
HRESULT GetTags(
                [in] SAFEARRAY(long) buffer, 
                [out, retval] long* retval);

The generated interop method in C#

int GetTags(System.Array buffer)
    Member of Cwise.IUser

So in this case do I have to create a SafeArray or can I simply pass a normal .Net Array to the COM method GetTags?

shane87
  • 3,090
  • 12
  • 51
  • 65

1 Answers1

8

use such a code for this

Array ar = Array.CreateInstance(typeof (int), 500);

instead of typeof(int) use your own data type, your COM object must say you what type is expecting.

Eugen
  • 2,934
  • 2
  • 26
  • 47
  • @Eugen: i think it is expecting typeof int however how should I know what size the array is to be? – shane87 May 04 '11 at 16:40
  • usually the COM object will need to tell you the size of array. almost any Windows API methods that work on same approach, if you send a null value they will return the size needed, after this you create the array and pass it to the method. Not sure how your COM is created. – Eugen May 04 '11 at 19:03
  • I edited the sample code I provided in my question if that makes more sense to you? – shane87 May 05 '11 at 10:17
  • I'd try to create an array of `size = 1` and see what happens. By not knowing the internal of this COM is hard to say something more. What does the help file say about this method? – Eugen May 05 '11 at 14:48
  • @Eugen Thanks for your response. The COM dll was compiled by a delphi developer where I work. The GetTags(Array buffer) method is supposed to populate an array of tags. As of now I can execute the method with a null value like you said, which returns the size of the array, I then create the array with that size and pass it to the method, however the array does not get populated?. The code has been tested and the method works fine in delphi. Any ideas? – shane87 May 05 '11 at 15:15
  • 1
    Nor sure I can help more here, best way to test it is to use the old VB6, it is very COM objects friendly. Another idea, instead of my code written above, just try to create a simple `int[] array = new int[mySize];` and pass it to the COM object. – Eugen May 05 '11 at 17:21