Since the bits field is a pointer to memory allocated in native code, you need to declare it as IntPtr in C # code.
struct MyImage { public int width; public int height; public IntPtr bits; }
If you want to access individual pixels in C # code, you need to write the GetPixel method, as in C ++ code.
Note that since the bits field is a pointer to memory allocated in native code, I expect the actual code to have a destructor for the structure that calls delete[] bits . Otherwise, your code will leak.
It also means that you will need to create and destroy instances in your own code and never do it in managed code. Is this the policy you are currently following? I suspect it is not based on the code that I see here.
You also need to reconsider passing struct by value. Do you really want to take a copy of it when you call this function? This means that you have two instances of the structure whose bits fields point to the same memory. But who owns this memory? This structure really needs to be passed by reference.
I think you have some problems in your design, but I donβt see enough code or know enough about your problem to give you specific advice.
In the comments, you state that your main goal is to port these bits from your C # code to C ++ code. I suggest you do it as follows:
MyImage* NewImage(int w, int h, Color* bits) { MyImage* img = new MyImage; img->w = w; img->h = h; img->bits = new Color[w*h]; for (int i=0; i<w*h; i++) img->bits[i] = bits[i]; return img; } void DeleteImage(MyImage* img) { delete[] img->bits; delete img; } void DoSomethingWithImage(MyImage* img) {
On the C # side, you can declare it as follows:
[DllImport(@"dllname.dll", CallingConvention=CallingConvention.Cdecl)] static extern IntPtr NewImage(int w, int h, int[] bits); [DllImport(@"dllname.dll", CallingConvention=CallingConvention.Cdecl)] static extern void DeleteImage(ImtPtr img); [DllImport(@"dllname.dll", CallingConvention=CallingConvention.Cdecl)] static extern void DoSomethingWithImage(ImtPtr img);