How to pass a long array from VB6 to C# thru COM

Viewed 987

I need to pass an array of int or long (doesn't matter) from a VB6 application to a C# COM Visible class. I've tried declaring the interface in C# like this:

void Subscribe([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_I4)]int[] notificationTypes)

void Subscribe(int[] notificationTypes)

But both of them raised a Function or interface markes as restricted, or the function uses an Automation type not supported in Visual Basic.

How should I declare the C# method?

2 Answers

I ran into this problem 9 years later. The solution I came up with is to pass a pointer to the first element of the array, along with the upper bound (UBound in VB6). Then iterate the pointer to the upper bound and put each element into a list.

on the vb6 side use

    Dim myarray(3) As float
    Dim ptr As integer
    Dim upperbound as integer

    myarray(0) = 0.1
    myarray(1) = 0.2
    myarray(2) = 0.3
    myarray(3) = 0.4

    ptr = VarPtr(myarray(0))
    upperbound = UBound(myarray)

    SetMyFloat(ptr, upperbound)
    

C# code


    public float MyFloat {get; set;}

    public unsafe void SetMyFloat(float* ptr, int ubound)
    {
        MyFloat = PointerToFloatArray(ptr, ubound);
    }

    public unsafe float[] PointerToFloatArray(float* ptr, int ubound)
    //this is to deal with not being able to pass an array from vb6 to .NET
    //ptr is a pointer to the first element of the array
    //ubound is the index of the last element of the array
    {
        List<float> li = new List<float>();
        float element;
        for (int i = 0; i <= ubound; i++)
        {
            element = *(ptr + i);
            li.Add(element);
        }
        return li.ToArray();
    }

Related