Mike Webb
Mike Webb

Reputation: 9003

How do I marshal a C# string array to a VB6 array?

I have a VB6 app that uses a C# COM DLL. In managed C++ I can write a function as follows:

array<String^>^ GetAManagedArray()
{
    //Do stuff and return a managed array
}

I can then assign the returned managed array to an array in VB6:

Sub MySub()
    Dim strArray() As String
    strArray = myComObject.GetAManagedArray
End Sub

This works fine in C++, but in C# the System.Array object is abstract and I can't seem to find the managed equivalent to the C++ array<>^. Also, in C# just returning string[] does not work.

What is the managed array equivalent in C#?

EDIT: Here is the exact code I have for the fucntions
The C# COM function:

public string[] OneTwoThree()
{
    return new string[] { "1", "2", "3" };
}

The VB6 function:

Private Sub Form_Load()
    Dim test As New ComObjectCSharp
    Dim strArr(), strTemp As String
    strArr = test.OneTwoThree
    strTemp = strArr(0) & " " & strArr(1) & " " & strArr(2)
    MsgBox strTemp
End Sub

The code fails on the fourth line of the VB6 code with the error "Compile error: Can't assign to array"

Upvotes: 2

Views: 2862

Answers (3)

Hans Passant
Hans Passant

Reputation: 941387

The strArr() variable is not actually an array of strings. It is an array of variants. Fix:

Dim strArr() As String
strArr = test.OneTwoThree

Now it is the same as your first snippet.

Upvotes: 7

ivo s
ivo s

Reputation: 144

My guess would be test.OneTwoThree returns a single string not an array of strings. Try Dim strArr instead of Dim strArr() If that works you have to find out what is the delimiter that the proxy for the C# function returned (sometimes marshaling of arrays doesn't necessary get proper/expected termination in client code enviournment)

Upvotes: 0

EMP
EMP

Reputation: 61971

If you're looking for the C# syntax to create an array it's new string[5] for an array of length 5, initialised with nulls or new string[] { "one", "two" } for an array with the specified values.

Aside from that, you'd have to be more specific about what "doesn't work" for us to help you.

Upvotes: 0

Related Questions