【问题标题】:How to send a double array from C# to C++如何将双数组从 C# 发送到 C++
【发布时间】:2011-07-26 21:14:08
【问题描述】:

在我的 C# 代码中,我有以下数组:

var prices = new[] {1.1, 1.2, 1.3, 4, 5,};

我需要将它作为参数传递给我的托管 C++ 模块。

var discountedPrices = MyManagedCpp.GetDiscountedPrices(prices) ;

GetDiscountedPrices 的签名应该是什么样子的?最琐碎的情况下,当折扣价等于价格时,C++方法GetDiscountedPrices应该是怎样的?

编辑:我设法让它编译。我的 C# 代码是这样的:

    [Test]
    public void test3()
    {
        var prices = new ValueType[] {1.1, 1.2, 1.3, 4, 5,};
        var t = new TestArray2(prices , 5);
    }

我的 C++ 代码构建:

        TestArray2(     
        array<double^>^ prices,int maxNumDays)
    { 
        for(int i=0;i<maxNumDays;i++)
        {
// blows up at the line below
            double price = double(prices[i]);
        }

但是我遇到了运行时错误:

System.InvalidCastException : 指定的强制转换无效。

编辑:凯文的解决方案奏效了。我还找到了一个有用的链接:C++/CLI keywords: Under the hood

【问题讨论】:

  • 为什么^double^ 中?很明显,您不能将double^ 转换为double。你为什么要这样做?
  • 这是 C++/CLI,而不是“托管 C++”。

标签: c# c++ arrays c++-cli


【解决方案1】:

您的托管函数声明在头文件中将如下所示:

namespace SomeNamespace {
    public ref class ManagedClass {
        public:
        array<double>^ GetDiscountedPrices(array<double>^ prices);
    };
}

这是上述函数的一个示例实现,它只是从输入数组中的每个价格中减去一个硬编码值,并将结果返回到一个单独的数组中:

using namespace SomeNamespace;

array<double>^ ManagedClass::GetDiscountedPrices(array<double>^ prices) {

    array<double>^ discountedPrices = gcnew array<double>(prices->Length);
    for(int i = 0; i < prices->Length; ++i) {
        discountedPrices[i] = prices[i] - 1.1;
    }
    return discountedPrices;
}

最后,从 C# 调用它:

using SomeNamespace;

ManagedClass m = new ManagedClass();
double[] d = m.GetDiscountedPrices(new double[] { 1.3, 2.4, 3.5 });

**请注意,如果您的托管 C++ 函数将数组传递给本机函数,则它需要编组数据以防止垃圾收集器接触它。不知道你的原生函数是什么样子的,很难展示一个具体的例子,但你可以找到一些很好的例子here

【讨论】:

    【解决方案2】:

    由于您使用托管 C++,我相信您希望 GetDiscountedPrices 的签名为:

    array<double>^ GetDiscountedPrices(array<double>^ prices);
    

    【讨论】:

    • 这不编译:不能在没有顶级'^'的情况下使用这里的类型
    • 签名应该使用array&lt;float&gt;^,注意克拉。也应该是double :)
    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 2012-02-24
    • 2020-02-28
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多