gpt4 book ai didi

c# - 如何将 double 组从 C# 发送到 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:48:20 25 4
gpt4 key购买 nike

在我的 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

最佳答案

您的托管函数声明在头文件中看起来像这样:

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++ 函数将数组传递给 native 函数,它将需要编码数据以防止垃圾收集器接触它。在不知道您的 native 函数是什么样子的情况下很难显示具体示例,但您可以找到一些很好的示例 here .

关于c# - 如何将 double 组从 C# 发送到 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6836704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com