目前,我正在尝试通过 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
最佳答案
不能在 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).ToArray();
}
关于c# - 如何通过 COM 互操作将 VBA 变量数组数据类型传递到 C# 方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60775491/