我有一个非托管代码和C#UI的C++ DLL。有一个从C++ DLL导入的函数,该函数采用write-by-me结构作为参数。编组结构包含int和int []从C#到C++
编组结束(MyImage)从C#到C++后,我可以访问其中的int []数组的内容,但内容是不同的。我不知道我在这里失去了什么,因为我花了很长时间,并尝试了一些技巧来解决这个问题(显然不够)。
MYIMAGE结构在C#:
[StructLayout(LayoutKind.Sequential)]
struct MyImage
{
public int width;
public int height;
public int[] bits; //these represent colors of image - 4 bytes for each pixel
}
MYIMAGE结构在C++:
struct MyImage
{
int width;
int height;
Color* bits; //typedef unsigned int Color;
MyImage(int w, int h)
{
bits = new Color[w*h];
}
Color GetPixel(int x, int y)
{
if (x or y out of image bounds) return UNDEFINED_COLOR;
return bits[y*width+x];
}
}
C#函数声明与MYIMAGE作为参数:
[DLLImport("G_DLL.dll")]
public static extern void DisplayImageInPolygon(Point[] p, int n, MyImage texture,
int tex_x0, int tex_y0);
C++实现
DLLEXPORT void __stdcall DisplayImageInPolygon(Point *p, int n, MyImage img,
int imgx0, int imgy0)
{
//And below they have improper values (i don't know where they come from)
Color test1 = img.GetPixel(0,0);
Color test2 = img.GetPixel(1,0);
}
因此,在调试问题时,我注意到C++结构中的MyImage.bits数组包含不同的数据。
我该如何解决?
是否有可能创建一个IntPtr int []数组没有不安全的代码?这个结构只有一个存在的目的 - >将图像传递给C++层,在那里我可以处理它。你是说我应该在IntPtr中传递整个结构? –
在这种情况下,我不会在C#中声明结构。只需在传递数据的本地代码中调用一个函数,并创建本地结构。 –
你说什么为我工作。还有1个问题:当我把它看作是正确的,当作为函数参数传递时,int []数组被整理为int *而没有问题,并且当数组作为int []传递给结构时,这不起作用?难道我们不能强制程序在结构内对待这个数组,就好像它将被作为参数传递给函数一样吗? –