user3551497
user3551497

Reputation:

How can I pass VBA variant array data type through COM interop into C# method

Currently I am trying to pass a variant data type array into a c# method through the COM interop. The issue is, passing it as:

[MarshalAs(UnmanagedType.SafeArray)

However this doesn't seem to be working, does anyone have any tips of how I could pass this as a parameter?

Here is my full c# source:

using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;

namespace ExpandExcel
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class ExpandExcelStandard
    {
        #region Public Static Methods

        [return: MarshalAs(UnmanagedType.SafeArray)]
        public static T[] RemoveDuplicates<T>([MarshalAs(UnmanagedType.SafeArray)] ref T[] arr)
        {
            // Creates a hash set based on arr
            HashSet<T> set = new HashSet<T>(arr);
            T[] resultArr = new T[set.Count];
            set.CopyTo(resultArr);
            return resultArr; // Return the resultArr
        }

        #endregion
    }
}

Here is my full VBA source:

Sub main()
    Dim arr(1000000) As Variant

    Dim ExpandExcel As ExpandExcelStandard
    Set ExpandExcel = New ExpandExcelStandard

    For i = 0 To UBound(arr)
        Randomize
        arr(i) = Int((1000000 + 1) * Rnd)
    Next i

    Dim resultArr() As Variant

    resultArr = ExpandExcel.RemoveDuplicates(arr)
End Sub

Upvotes: 2

Views: 710

Answers (1)

Simon Mourier
Simon Mourier

Reputation: 138841

You can't use generics with COM, you can't use static functions, etc. Here is a similar code that should work:

VB

Sub main()
    Dim arr(1000000) As Variant

    For i = 0 To UBound(arr)
        Randomize
        arr(i) = Int((1000000 + 1) * Rnd)
    Next i

    Set ExpandExcel = CreateObject("ExpandExcelStandard") // I used late binding but early is fine too
    resultArr = ExpandExcel.RemoveDuplicates(arr)
End Sub

C#

[ProgId("ExpandExcelStandard")] // because I wanted late binding, I declared a progid
[ComVisible(true)]
public class ExpandExcelStandard
{
    // .NET object (w/o any Marshal spec) is passed as an automation Variant
    public object[] RemoveDuplicates(object[] arr) => new HashSet<object>(arr).ToArray();
}

Upvotes: 2

Related Questions