在C#中调用C++dll

 

 

 

 一、C++函数中的double** 参数

C++ DLL中的接口如下:

int gray2energy(double** data,const int length,const double gamma);

在C#中调用C++:

方式1,通过指针的方式在C#也用double**对应C++ 中的double**

 [DllImport("xxxx.dll", CallingConvention = CallingConvention.Cdecl)]
 public unsafe static extern int gray2energy(double** dd, int length, double gamma);

方式2:

[DllImport("xxxx.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int gray2energy(ref IntPtr dd, int lenght, double gamma);

 

若采用第一种方式,可这样实现:

//已知doubles
double[] doubles = byteToDouble(bts);
if (doubles == null || doubles.Length == 0)
    return;
unsafe
{
    fixed (double* doublePtr = doubles)
    {
        double** doubdoubPtr = &doublePtr;
        int res = gray2energy(doubdoubPtr, doubles.Length, 2);
    }
}

 

若采用第二种方式,可这样实现:

//申请内存大小
double[] resDoubles = new double[doubles.Length];
int size = Marshal.SizeOf(typeof(double)) * doubles.Length;
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
    Marshal.Copy(doubles, 0, ptr, doubles.Length);
    int res = gray2energy(ref ptr, doubles.Length, 2);
    Marshal.Copy(ptr, resDoubles, 0, doubles.Length);
}
finally
{
    Marshal.FreeHGlobal(ptr);
}

 

二、C++函数中的double* 参数

C++ DLL中的接口如下:

Bin_Gen(char* binName,double* R,double* G,double* B,char* param)

C#中调用:

方式一:

[DllImport("Vision.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int Bin_Gen(string path, 
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] double[] r, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] double[] g, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] double[] b,
string param);

或方式二:

public extern unsafe static int Bin_Gen(string path, double* r, double* g, double* b, string param);

采用方式一,直接传入c#中的double[]即可。

采用方式二,可这样实现:

// 已知double[] binData_R、double[] binData_G、double[] binData_B、int nResult
unsafe
{
    fixed (double* r_ptr = binData_R)
    {
        fixed (double* g_ptr = binData_G)
        {
            fixed (double* b_ptr = binData_B)
            {
                nResult = Bin_Gen(hexPath, r_ptr, g_ptr, b_ptr, "")
            }
        }
    }
}

 

posted @ 2024-08-23 15:06  春天花会开,  阅读(75)  评论(0)    收藏  举报