C#与C++之间的二维(多维)数组传递

wjf8882300 2009-04-14 06:14:58
我在一个解决方案里面分别建立了一个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];
}
}
...全文
1199 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjhiphop2006 2009-04-15
  • 打赏
  • 举报
回复
此人素质较低,不要回答他的问题
wjf8882300 2009-04-15
  • 打赏
  • 举报
回复
小项目还可以吧,好象代码多了无法编译通过!
龙宜坡 2009-04-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 cppfaq 的回复:]
直接unsafe,然后用指针算了
[/Quote]

这样来比较划算
zjhiphop2006 2009-04-15
  • 打赏
  • 举报
回复
up。。
wjf8882300 2009-04-15
  • 打赏
  • 举报
回复
以前我也这么想过,但我C++后台处理的代码较多,也比较复杂,全部写在一起很乱,也不易于维护
wjf8882300 2009-04-15
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 zjhiphop2006 的回复:]
此人素质较低,不要回答他的问题
[/Quote]
老兄,咱们私人恩怨,不要拿到群里来谈好吗?
cppfaq 2009-04-14
  • 打赏
  • 举报
回复
直接unsafe,然后用指针算了

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧