c# - 无法访问/转换 System.Double[*] 对象

标签 c# arrays pinvoke com-interop

我使用一个界面来访问一个旧的应用程序。从这个应用程序我有一些我无法访问的“双数组”。返回类型被声明为虚拟动态。每当我访问数组时,我都会遇到异常。

关于 this question我发现这可能是因为错误的索引数组。所以我已经尝试了建议的解决方案,但正如我所说,如果没有出现异常,我什至无法访问数组一次。

知道错误可能是什么吗?

用 Hans 方法编写代码:

var dataSetValues = dataSet.DoubleArray;
var result = ConvertDoubleArray(dataSetValues); // <<<<<< This is where I get an exception

public static double[] ConvertDoubleArray(Array arr)
{
    if (arr.Rank != 1) 
        throw new ArgumentException();

    var retval = new double[arr.GetLength(0)];
    for (int ix = arr.GetLowerBound(0); ix <= arr.GetUpperBound(0); ++ix)
        retval[ix - arr.GetLowerBound(0)] = (double) arr.GetValue(ix);
    return retval;
}

DoubleArray的接口(interface)声明:

public virtual dynamic DoubleArray { get; set; }

运行时类型信息: enter image description here

异常(exception):

System.InvalidCastException: Unable to cast object of type 'System.Double[*]' to type 'System.Double[]'. at CallSite.Target(Closure , CallSite , VirtualEnvironmentManager , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1) at FormulaTestExecutor.Common.VirtualEnvironmentManager.CreateVirtualStructure(Formula formula) in D:\Develop\TFS\Main\tools\FormulaMTest\FormulaTestExecutor\FormulaTestExecutor\Common\VirtualEnvironmentManager.cs:line 55

异常堆栈跟踪:

FormulaTestExecutor.exe!FormulaTestExecutor.Common.VirtualEnvironmentManager.CreateVirtualStructure(FormulaTestExecutor.Model.Formula formula = {FormulaTestExecutor.Model.Formula}) Line 55 C# Symbols loaded. FormulaTestExecutor.exe!FormulaTestExecutor.Program.Main(string[] args = {string[0]}) Line 18 C# Symbols loaded.

最佳答案

你必须这样做:

var dataSetValues = dataSet.DoubleArray; // dataSetValues is dynamic
var result = ConvertDoubleArray((Array)(object)dataSetValues);

原因是 DoubleArray 的“动态”类型(可能是在您添加 COM 引用时在界面中自动定义的)。这是一个super smart thing它试图自己完成从 System.Double[*]System.Double[] 的转换,但它不够聪明,无法做到这一点(它无法读取StackOverflow 的答案……还没有)

因此,您必须要求它“按原样”传递对象,以便能够将其直接传递给 CLR 低级转换,它可以对数组执行 System.Double[*] w/崩溃。获得数组后,您可以重新使用 ConvertDoubleArray 实用程序。

关于c# - 无法访问/转换 System.Double[*] 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867204/

相关文章:

c# - 为什么 Font 是不可变的?

c# - 如何判断默认打印机何时更改?

c# - 获取从 native dll 到 C# 应用程序的结构数组

c# - ASP.NET MVC3 Controller AOP 代理不拦截所有方法,只有 IController.Execute

c# - 即时修改 SQL 结果?

php - 如何将 php 枚举转换为数组?

java - 在不使用对象的情况下对不同数据类型的多个数组进行排序

Javascript - 有没有更有效的方法来创建数组数组? - 提供示例

ssize_t 的 C# 模拟类型

c# - WCF 自定义身份验证不起作用