一个难倒无数高手(发在微软新闻组上到现在还没好的解决方案)的问题,有关数据转换
weijl 2003-07-29 03:52:57 分别有三个结构体,如下:
[ StructLayout( LayoutKind.Sequential )]
public struct ONL_POINT //点
{
public int x, y;
}
[ StructLayout( LayoutKind.Sequential )] //线
public struct ONL_STROKE
{
public IntPtr pPoint;
public int pointNum;
}
[ StructLayout( LayoutKind.Sequential )] //字
public struct ONL_STROKES
{
public IntPtr pStroke;
public int strokeNum;
}
ONL_POINT[] points1 = new ONL_POINT[2];
points1[0].x = 1;
points1[0].y = 1;
points1[1].x = 99;
points1[1].y = 99;
ONL_POINT[] points2 = new ONL_POINT[2];
points2[0].x = 99;
points2[0].y = 1;
points2[1].x = 1;
points2[1].y = 99;
ONL_STROKE[] strokes = new ONL_STROKE[2];
int size = Marshal.SizeOf( typeof(ONL_POINT) );
IntPtr buffer1 = Marshal.AllocHGlobal(size*points1.Length );
for (int i = 0; i < points1.Length; i++)
{
IntPtr temp;
temp = new IntPtr( buffer1.ToInt32() + i * size );
Marshal.StructureToPtr( points1[i], temp, false );
}
strokes[0].pPoint = buffer1;
strokes[0].pointNum = points1.Length;
IntPtr buffer2 = Marshal.AllocHGlobal( size * points2.Length );
for (int i = 0; i < points2.Length; i++)
{
IntPtr temp;
temp = new IntPtr( buffer2.ToInt32() + i * size );
Marshal.StructureToPtr( points2[i], temp, false );
}
strokes[1].pPoint = buffer2;
strokes[1].pointNum = points2.Length;
ONL_STROKES stroke_data;
size = Marshal.SizeOf( typeof(ONL_STROKE) );
IntPtr buffer3 = Marshal.AllocHGlobal( size * strokes.Length );
int[] buffer4 = new int[strokes.Length];
for (int i = 0; i < strokes.Length; i++)
{
IntPtr temp;
temp = new IntPtr( buffer3.ToInt32() + i * size );
Marshal.StructureToPtr( strokes[i], temp, false );
buffer4[i] = temp.ToInt32();
}
IntPtr buffer5 = Marshal.AllocHGlobal( IntPtr.Size * strokes.Length );
Marshal.Copy(buffer4, 0, buffer5, strokes.Length);
stroke_data.pStroke = buffer5;
stroke_data.strokeNum = strokes.Length;
以上是将代表二条线的四点转换为ONL_STROKES,因为要调用dll,dll接口为ONL_STROKES,所以要如此复杂的转换,这个转换肯定对。问题是反过来,将ONL_STROKES型转换为ONL_POINT型中的x,y就有问题了。我的写法如下
假设ONL_STROKES strokes已有值
ONL_STROKE[] stroke = new ONL_STROKE[strokes.strokeNum];
int size = Marshal.SizeOf( typeof(ONL_STROKE) );
for(int i = 0; i < strokes.strokeNum;i++ )
{
IntPtr temp;
temp = new IntPtr( strokes.pStroke.ToInt32() + i*size );
stroke[i] = (ONL_STROKE)Marshal.PtrToStructure(temp,typeof(ONL_STROKE));
}
ONL_POINT[][] point = new ONL_POINT[strokes.strokeNum][];
size = Marshal.SizeOf( typeof(ONL_POINT) );
for(int j = 0; j < strokes.strokeNum;j++ )
{
point[j] = new ONL_POINT[stroke[j].pointNum];
for(int k = 0; k <stroke[j].pointNum; k++ )
{
IntPtr temp;
temp = new IntPtr( stroke[j].pPoint.ToInt32() + k * size );
point[j][k] = (ONL_POINT)Marshal.PtrToStructure(temp, typeof(ONL_POINT));
}
}
for(int j = 0; j < strokes.strokeNum;j++ )
{
for(int k = 0; k <stroke[j].pointNum; k++ )
{
int a = point[j][k].x;
a = point[j][k].y;
}
}
但是一运行数据都不对,请问各位高手如何解决?