Marshall C# string[] to VBScript
See the question and my original answer on StackOverflowOther languages do support it, but you cannot use an array of strings from VBScript (internally and in the type library it will be represented as a SAFEARRAY of BSTR).
It only support an array of objects, but you can also use the old ArrayList .NET class (which also allows for each
type enumeration), for example in C#:
public interface IComMethods
{
ArrayList Interlockings { get; }
object[] InterlockingsAsObjects { get; }
}
public class MyClass: IComMethods
{
public ArrayList Interlockings => new ArrayList(new string[] { "abc", "def" });
public object[] InterlockingsAsObjects => new object[] { "abc", "def" };
}
And in VBScript:
set x = CreateObject("MyClassLibrary.MyClass")
' ArrayList
WScript.Echo "Count " & x.Interlockings.Count
for each il in x.Interlockings
WScript.Echo il
next
WScript.Echo x.Interlockings.Item(1) ' def
' array of objects
ar = x.InterlockingsAsObjects
WScript.Echo "Count " & ubound(ar) - lbound(ar) + 1
for i = lbound(ar) to ubound(ar)
WScript.Echo ar(i)
next
WScript.Echo ar(1) ' def
Another trick is to declare a COM interface as VBScript expects, but implement it privately so it looks better to .NET callers, something like this:
public class MyClass : IComMethods
{
// better for .NET clients
public string[] Interlockings => new string[] { "abc", "def" };
// explicit implementation
object[] IComMethods.Interlockings => Interlockings.ToArray<object>();
}
public interface IComMethods
{
object[] Interlockings { get; }
}
Obviously, you can do the same with ArrayList
instead of object[]
.