将字符串数组从VB6传递到c# .net

本文关键字:net VB6 字符串 数组 | 更新日期: 2023-09-27 18:01:58

如何通过COM互操作将VB6字符串数组[假设,s= array ("a", "b", " C ", "d")]传递给c# .Net ?

我试图实现将c#字符串数组传递给VB和VB字符串数组传递给c#,如下c# ->VB工作良好,但其他方式(VB=> c#)给出一个编译错误,称为

标记为受限的函数或接口,或者函数使用visualbasic中不支持的自动化类型

下面的代码

c#

public interface ITest   
{ 
     string[] GetArray();
     void SetArray(string[] arrayVal );
}
public class Test : ITest 
{
    string[] ITest.GetArray() {                                //Working fine
        string[] stringArray = { "red ", "yellow", "blue" };
        return stringArray;
    }
}
void ITest.SetArray(string[] arrayVal) //Giving an issue
{
   string[] stringArray1 = arrayVal;
}

VB

Dim str As Variant
Debug.Print ".NET server returned: "    
For Each str In dotNETServer.GetArray      'dotNETServer=TestServer.Test
    Debug.Print str
Next
Dim arr(3) As String
arr(1) = "Pahee"
arr(2) = "Tharani"
arr(3) = "Rathan"
dotNETServer.SetArray (arr) 'This one causing the compile error which I mentioned earlier

更新:::::::

在c#中需要传递数组作为引用。在接口和方法

中更改它
void SetArray(ref string[] arrayVal ); //ref added

将字符串数组从VB6传递到c# .net

封送为适当的类型将解决您的问题。注意

下面的封送处理和ref关键字更改
void ITest.SetArray([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VT_BSTR)] ref string[] arrayVal)
{
   string[] stringArray1 = arrayVal;
}

我根据你的代码和问题做了这个解决方案,你不能从VB6获取数据。如果上面的解决方案不适合您,请尝试找到适合您的应用程序的数组类型/子类型http://msdn.microsoft.com/en-us/library/z6cfh6e6(v=vs.110).aspx

您的问题在Vb6代码中:

dotNETServer.SetArray (arr)

这实际上是强迫arr按值传递,因为它被括号括起来,没有Call关键字。

你想这样做:

Call dotNETServer.SetArray(arr)

dotNETServer.SetArray arr