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

耗尽温柔 提交于 2019-12-02 06:06:38

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