C#与C++之间的二维(多维)数组传递
我在一个解决方案里面分别建立了一个C++项目和一个C#项目,现在需要把C#项目里面的二维数组传递到C++中,问怎么做?
我原来的做法是进行数组之间的转换,但感觉这么做比较笨,不知有没有其他的好方法?
C#中
/// 声明委托
/// </summary>
/// <param name="spOriginData">待处理小波子带图像</param>
/// <param name="width">图像宽</param>
/// <param name="height">图像高</param>
/// <param name="param">梯度参数</param>
delegate void water(ref short spOriginData, int width, int height, ref double param,ref short result);
private static IntPtr instance;//对C++操作的句柄
//图像处理函数
public void Water()
{
short[,] spOriginData = model.SpTransData;//获取图像数据
int width = spOriginData[0].Length;//图像宽度
int height = spOriginData.Length;//图像长度
instance = DLLWrapper.LoadLibrary(dllPath);//寻找dll函数入口
water wt = (water)DLLWrapper.GetFunctionAddress(instance, "Water", typeof(water));//获取Water函数地址
//如果C++中指定函数不存在则释放dll句柄
if (wt == null)
{
DLLWrapper.FreeLibrary(instance);
return;
}
double[] param = model.ParamGrad;//获取参数
if (param == null)
{
param = new double[3];
param[0] = 0.1;
param[1] = 0.79;
param[2] = 0.82;
}
//定义一个结果集用于存储C++处理后的结果
short[,] result = new short[height, width];
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
{
result[i, j] = 0;
}
//调用C++里面的函数
wt(ref data[0, 0], width, height, ref param[0], ref result[0, 0]);
//释放句柄
DLLWrapper.FreeLibrary(instance);
}
}
C++中
extern "C" __declspec(dllexport) void Water(short *OriginalImage,int width,int height,double *param,short *result);
void Water(short *OriginalImage,int width,int height,double *param,short *result)
{
//将存储原始图像的一维数组数据转存到二维数组
short** oldImageGrad=new unsigned char *[height];
for(int i=0;i<height;i++)
{
oldImageGrad[i]=new unsigned char [width];
}
for(int i=0;i<height;i++)
for(int j=0;j<width;j++)
{
oldImageGrad[i][j]=OriginalImage[i*width+j];
}
//调用函数操作
WaterSherd *ws=new WaterSherd();
ws->Watershed(oldImageGrad,LabelImage,height,width,param);//LabelImage是一个二维数组用于存储处理后的数据
//将LabelImage存入一维数组result
for(int i=0;i<height;i++)
for(int j=0;j<width;j++)
{
result[i*width+j]=LabelImage[i][j];
}
}