Loading and Passing JScript Arrays from/to C# (not C) COM Component

后端 未结 1 1090
抹茶落季
抹茶落季 2021-01-25 07:05

I have looked at tutorials on jscript arrays, but not seeing it yet. I saw something similar asked but involving Win32 code not .NET.

Wondering, how do I pass arrays bac

相关标签:
1条回答
  • 2021-01-25 07:30

    Microsoft JScript engine implements JavaScript arrays as IDispatchEx objects. From C#, they can be manipulated via reflection or as dynamic objects (with dynamic, it's only possible to access properties and methods like length, push() etc., but not reference actual elements by their indices). Example:

    JavaScript:

    var T = new ActiveXObject("MySimulator.World"); 
    
    var ar = ["a", "b", "c"];
    
    T.MyFunction(ar);
    

    C#:

    public void MyFunction(object array)
    {
        dynamic dynArray = array;
        int length = dynArray.length;
        dynArray.push("d");
    
        SetAt(array, 1, "bb"); 
    
        Console.WriteLine("MyFunction called, array.length: " + length);
        Console.WriteLine("array[0]: " + GetAt(array, 0));
        Console.WriteLine("array[1]: " + GetAt(array, 1));
        Console.WriteLine("array[3]: " + GetAt(array, 3));
    }
    
    static object GetAt(object array, int index)
    {
        return array.GetType().InvokeMember(index.ToString(),
            System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetProperty,
            null, array, new object[] { });
    }
    
    static object SetAt(object array, int index, object value)
    {
        return array.GetType().InvokeMember(index.ToString(),
            System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty,
            null, array, new object[] { value });
    }
    

    Output:

    MyFunction called, array.length: 3
    array[0]: a
    array[1]: bb
    array[3]: d
    
    0 讨论(0)
提交回复
热议问题