Passing string array from VB6 to C#.net

安稳与你 提交于 2019-12-01 02:12:12

问题


How to pass a VB6 string array [Assume, s =Array("a", "b", "c", "d")] to C#.Net through COM Interop?

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 "Function or interface marked as restricted, or the function uses an automation type not supported in visual basic" . My code below

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

Update: ::::::

We need to pass the array as reference in C#. Change it in the interface and method

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

回答1:


Marshaling to appropriate type will solve your problem. Note marshaling and ref keyword change below

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. 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




回答2:


Your issue was in the Vb6 code:

dotNETServer.SetArray (arr)

This is actually forcing arr to be passed by value because it is enclosed by parentheses with no Call keyword.

You want to do this:

Call dotNETServer.SetArray(arr)

or

dotNETServer.SetArray arr


来源:https://stackoverflow.com/questions/23507416/passing-string-array-from-vb6-to-c-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!