简体   繁体   English

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

[英]Passing string array from VB6 to C#.net

How to pass a VB6 string array [Assume, s =Array("a", "b", "c", "d")] to C# .Net through COM Interop?如何通过 COM 互操作将 VB6 字符串数组 [Assume, s =Array("a", "b", "c", "d")] 传递给 C# .Net?

I tried to implement passing C# string array to VB and VB string array to C# as below C#->VB working fine but other way (VB=>C#) giving a compile error called我尝试实现将 C# 字符串数组传递给 VB,并将 VB 字符串数组传递给 C#,如下所示 C#->VB 工作正常,但其他方式 (VB=>C#) 给出了一个名为

Function or interface marked as restricted, or the function uses an automation type not supported in visual basic标记为受限的函数或接口,或函数使用了 Visual Basic 不支持的自动化类型

My code below我的代码如下

C# 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 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

Update: ::::::更新: ::::::

We need to pass the array as reference in C# .我们需要在 C# 中将数组作为引用传递 Change it in the interface and method在接口和方法中改变它

void SetArray(ref string[] arrayVal ); //ref added

Marshaling to appropriate type will solve your problem.编组为适当的类型将解决您的问题。 Note marshaling and ref keyword change below注意下面的编组和 ref 关键字更改

void ITest.SetArray([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VT_BSTR)] ref string[] arrayVal)
{
   string[] stringArray1 = arrayVal;
}

I made this solution based on your code and issue that you are not able to fetch data from VB6.我根据您的代码和您无法从 VB6 获取数据的问题制作了此解决方案。 If above solution does not work for you the do try finding the array type/subtype suitable for your application here http://msdn.microsoft.com/en-us/library/z6cfh6e6(v=vs.110).aspx如果上述解决方案对您不起作用,请尝试在此处找到适合您的应用程序的数组类型/子类型http://msdn.microsoft.com/en-us/library/z6cfh6e6(v=vs.110).aspx

Your issue was in the Vb6 code:您的问题出在 Vb6 代码中:

dotNETServer.SetArray (arr)

This is actually forcing arr to be passed by value because it is enclosed by parentheses with no Call keyword.这实际上是强制arr按值传递,因为它被括号括起来,没有Call关键字。

You want to do this:你想这样做:

Call dotNETServer.SetArray(arr)

or或者

dotNETServer.SetArray arr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM