How to correctly marshal VB-Script arrays to and from a COM component written in C#

前端 未结 3 732
萌比男神i
萌比男神i 2020-12-03 03:30

I\'m building a COM object in C# (.Net 4.0) to be used in an classic asp site. Now I\'d like to know what\'s the proper way to marshal VB-Script arrays (single and multidime

3条回答
  •  不知归路
    2020-12-03 04:08

    A bit late, but in case someone needs this in the future:

    I managed to pass an ArrayList of Hashtables to Classic ASP. It seems that types of the namespace System.Collections can be passed, System.Collections.Generic can not.

    .cs-File:

    using System;
    using System.Runtime.InteropServices;
    using System.Collections;
    
    namespace Test
    {
        [ComVisible(true)]
        [Guid("D3A3F3E7-F1A9-4E91-8D7B-D9E19CF38165")]
        public interface iDemo
        {
            [return: MarshalAs(UnmanagedType.Struct, SafeArraySubType = VarEnum.VT_ARRAY)]
            ArrayList DemoMethod();
        }
    
    
        [ProgId("Test.Demo")]
        [ClassInterface(ClassInterfaceType.None)]
        [Guid("F53257DD-9275-4D6C-A758-EFF6932FF8B2")]
        [ComVisible(true)]
        public class Demo : iDemo
        {
            [ComVisible(true)]
            public ArrayList DemoMethod()
            {
                ArrayList Results = new ArrayList();
    
                for (int i = 0; i < 5; i++)
                {
                    Hashtable table = new Hashtable();
                    table.Add("Text", "Test"+i);
                    table.Add("Number", i);
                    Results.Add(table);
                }
                return Results;
            }
        }
    }
    

    .asp-File:

    <%
    set test = server.createObject("Test.Demo")
    set results = test.DemoMethod()
    response.write "Results: " & results.count & "

    " for each result in results response.write result("Text") & "
    " response.write result("Number") & "

    " next %>

    Output:

    Results: 5
    
    Test0
    0
    
    Test1
    1
    
    Test2
    2
    
    Test3
    3
    
    Test4
    4
    

    This is pretty convenient if you have to pass a lot of data from C# to Classic ASP (Should work in VB Script too, but not tested), as you can loop through objects with any attributes. Also didn't test the other way around, because I only needed to pass data from C# to Classic ASP.

提交回复
热议问题