I know that this question has been discussed many times here, but I could not find the answer for my specific situation.
I need to call an unmanaged C method in C # that takes a pointer to a struct object (I don't say C smoothly:
int doStuff(MYGRID* grid, int x);
But the structure itself refers to another struct object:
struct MYGRID { int hgap; int vgap; MYIMAGE* image; } struct MYIMAGE { int res; int width; int height; }
And I also need to set the direct image pointer as follows:
MYGRID* pGrid = new MYGRID; MYIMAGE* pImage = new MYIMAGE; pGrid->image = pImage;
So my question is: in the C # code should I use the โstructโ object and pass it โrefโ, as the P / Invoke Interop Assistant tells me? This means the following code:
MyGrid myGrid = new MyGrid(); MyImage myImage = new MyImage(); myGrid.image = Marshal.AllocHGlobal(Marshal.SizeOf(image)); // A IntPtr in my struct myGrid.image = Marshal.StructureToPtr(image, myGrid.image, false); doStuff(ref myGrid, 0);
Or I could use a "class" instead of a "struct" to have a very simple following code:
MyGrid myGrid = new MyGrid(); MyImage myImage = new MyImage(); myGrid.image = myImage; doStuff(myGrid, 0);
In the first case, I use "IntPtr" in my MyGrid structure and just the MyImage object in the second case.
Eric David
source share