在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 @   春天花会开,  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示