【问题标题】:How to pass a long array from VB6 to C# thru COM如何通过 COM 将长数组从 VB6 传递到 C#
【发布时间】:2012-07-13 04:16:58
【问题描述】:

我需要将一个 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# 方法?

【问题讨论】:

  • 嗯,这很奇怪。只需删除 [MarshalAs],无需您的帮助,该数组就已经被编组为 SAFEARRAY。如果您仍然遇到问题,我们需要查看其余的接口类型。
  • @HansPassant 是的,我查看了生成的 IDL,因为它在两种情况下都正确声明为 SAFEARRAY(long),所以我认为它一定是与 VB6 相关的问题。我还在调查。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 2012-08-21
      • 1970-01-01
      • 2023-04-11
      • 2013-02-19
      • 2012-10-22
      • 2011-11-23
      • 2021-07-10
      • 2010-11-20
      相关资源
      最近更新 更多