如何将c#双精度[]传递给需要常量双精度* pArr的c++函数?c++, c#

本文关键字:c++ 双精度 常量 pArr 函数 | 更新日期: 2023-09-27 18:02:50

我用c++写了一个函数:

MyFunc(const double* pArray, int length);

我需要传递一个非常量数组给它:

//C#
double[] myDoubleArray = new double[] { 1, 2, 3, 4, 5 };
MyFunc(myDoubleArray, 5);

当我这样做时,程序正在崩溃。

编辑:

//C# declaration
[DllImport(@"RTATMATHLIB.dll", EntryPoint = "?MyFunc@@YANPBNHHHH@Z")]
public static extern double MyFunc(double[] data, int length);
//C# usage
public static double MyFunc(double[] data)
{
    return MyFunc(data, data.Length);
}
//C++ export
__declspec(dllexport) double MyFunc(const double* data, int length);

//C++ signature
double MyFunc(const double* data, int length)
{
    return 0; //does not quite matter what it returns...
}

如何将c#双精度[]传递给需要常量双精度* pArr的c++函数?c++, c#

总是可以将非常量数组传递给需要常量数组的函数。数组的const限定符意味着函数不会修改数组的内容。在传递给函数之前,数组不需要是常量;由于声明

中的const,该函数不会修改内容。

一致性可以简单地添加。你的程序没有错。