从c# Array MarshalAs Problems中调用c++

Call C++ from C# Array MarshalAs Problems?

本文关键字:调用 c++ Problems MarshalAs Array      更新时间:2023-10-16

在c++库中有一个函数:

double MyFunc(double** data, int length)
{
    //data elements are accessed like this
    (*data)[i] = 5.0;
}

在c#中,我用这种方式访问这个函数:

//import
[DllImport(@"MYDLL.dll")]
public static extern double MyFunc(ref double[] data, int length);
//usage
MyFunc(ref data, data.Length);

这是愚蠢的,因为我宁愿写:

double MyFunc(double* data, int length)
{
    //data elements are accessed like this
    data[i] = 5.0;
}

问题是,我不知道如何从c#访问所需的c++函数…我不是很精通编组值…我该怎么做呢?

您可以直接传递一个double[]

如果您正在询问如何在c#中创建相同的函数,那么您正在询问c#中的unsafe代码检查这个和这个。

你的代码应该是:

unsafe double MyFunc(double* data, int length)
{
    //data elements are accessed like this
    data[i] = 5.0;
}