2012-09-14 38 views
2

我想传递一个整数数组从经典ASP到在C#中创建的DLL。如何将传统asp的整数数组传递给c#COM对象?

我有下面的C#方法:

public int passIntArray(object arr) 
{ 
    int[] ia = (int[])arr; 
    int sum = 0; 
    for (int i = 0; i < ia.Length; i++) 
     sum += ia[i]; 

    return sum; 
} 

我已经尝试了多种方法来ARR转换为int [],但没有取得任何成功。我的ASP代码:

var arr = [1,2,3,4,5,6]; 
var x = Server.CreateObject("dllTest.test"); 
Response.Write(x.passIntArray(arr)); 

我目前收到以下错误:

Unable to cast COM object of type 'System.__ComObject' to class type 'System.Int32[]'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface. 

谁能告诉我该怎么做还是告诉我不能这样做?

在这个非常有用的页面上使用代码http://www.add-in-express.com/creating-addins-blog/2011/12/20/type-name-system-comobject/我已经设法发现传递参数的类型是“JScriptTypeInfo”,如果它有任何用处的话。

如果我添加:

foreach (object m in arr.GetType().GetMembers()) 
    // output m 

我得到以下输出:

System.Object GetLifetimeService() 
System.Object InitializeLifetimeService() 
System.Runtime.Remoting.ObjRef CreateObjRef(System.Type) 
System.String ToString() 
Boolean Equals(System.Object) 
Int32 GetHashCode() 
System.Type GetType() 
+0

由于int []被Com Interop作为SAFEARRAY编组,所以它基本上是以下副本:http://stackoverflow.com/questions/5910538/how-to-create-a-safearray-in-windows-jscript –

+0

如果它是重复的,那么我不明白它,因为我不知道如何采取答案,使我的代码工作 – Graham

回答

1

正如SO item I suggested was a duplicate解释,你会因此改变你的ASP代码:

function getSafeArray(jsArr) 
{ 
    var dict = new ActiveXObject("Scripting.Dictionary");  
    for (var i = 0; i < jsArr.length; i++)  
    dict.add(i, jsArr[i]);  
    return dict.Items(); 
} 
var arr = [1,2,3,4,5,6]; 
var x = Server.CreateObject("dllTest.test"); 
Response.Write(x.passIntArray(getSafeArray(arr))); 

你还应该将您的C#方法签名更改为:

public int passIntArray(object[] arr) // EDITED: 17-Sept 

public int passIntArray([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_I4)] int[] arr) 

的一点是,你是不是真的试图去从JavaScript到C#,你从JavaScript将COM:你只能界面中的C#DLL可言,因为它是标记有ComVisible特性并使用ProgID在COM注册表中注册,Server.CreateObject可以查找。通过签名更改,您的DLL的COM暴露的接口将期望收到非托管的SAFEARRAY,上面的脚本代码是一种让JavaScript提供一个的方法,使用COM Scripting.Dictionary作为一种自定义封送拆收器。

+0

感谢您解释它,但它不起作用。我收到错误: Microsoft.JScript运行时错误'800a000d' 类型不匹配 在Response.Write行。我把这一行分成了几部分,它是导致错误的x.passIntArray位。将safearray变成一个变量可以正常工作。 – Graham

+0

按照上面我编辑的方法尝试修改后的C#方法签名,并查看是否成功调用了C#方法。然后您必须在方法内将元素转换为“int”。 (或者,您可以通过将您的C#方法参数归属于'[MarshalAs(UnmanagedType)'来帮助编组人员做正确的事情。SafeArray,SafeArraySubType = VT_I4)]') –

+0

我在哪里放置属性 - 我已经把它放在方法之前,它似乎很高兴,但它不喜欢VT_I4 - 在当前的情况下不存在 – Graham