如何将长数组从VB6传递到C#到COM

时间:2012-07-13 10:06:20

标签: c# .net vb6 interop com-interop

我需要将一个int或long数组(无关紧要)从VB6应用程序传递给C#COM Visible类。我试过在C#中声明这样的界面:

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

void Subscribe(int[] notificationTypes)

但他们两人都提出了Function or interface markes as restricted, or the function uses an Automation type not supported in Visual Basic

我应该如何声明C#方法?

2 个答案:

答案 0 :(得分:1)

如果你绝望,请在虚拟VB6 ActiveX dll项目中编写签名。然后通过Visual Studio或命令行工具生成vb6组件的.NET Interop版本。然后使用Reflector或dotPeek将代码拉出互操作程序集。这是漫长的过程,但它确实有效。

答案 1 :(得分:0)

我在 9 年后遇到了这个问题。我想出的解决方案是传递一个指向数组第一个元素的指针以及上限(VB6 中的 UBound)。然后迭代指向上界的指针,将每个元素放入一个列表中。

在vb6端使用

    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# 代码


    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();
    }