如何通过COM互操作将VBA变量数组数据类型传递到C#方法中

问题描述 投票:1回答:1

当前,我正在尝试通过COM互操作将变量数据类型数组传递给c#方法。问题是,将其传递为:

[MarshalAs(UnmanagedType.SafeArray)

但是这似乎不起作用,没有人提示我如何将其作为参数传递?

这是我完整的C#来源:

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
    }
}

这是我完整的VBA来源:

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
c# .net vba com com-interop
1个回答
1
投票

您不能将泛型用于COM,不能使用静态函数,等等。这是应该起作用的类似代码:

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.Cast<object>()).ToArray();
}
© www.soinside.com 2019 - 2024. All rights reserved.