Declare native types inside cli class?
I have
public ref class Test
inside this class, I:
int frameWidth;
int frameHeight;
int frameStride;
When I try to compile this, I get the error:
error C2664: 'GetImageSize' : cannot convert parameter 1 from 'cli::interior_ptr<Type>' to 'int *'
GetImageSize is a built-in function and it only works if I move the 3 integer declaration above outside the class or inside the block that calls GetImageSize.
How can I solve this?
Those 3 ints should be accessed by more than one function inside the class, right now I got it working because I moved them outside the class, but I don't believe I believe they become global.
According to this post , the reason you see this is because the ints are inside a ref class that can be moved around the heap by the garbage collector at will, the ints address might have changed and you wouldn't be told.
To overcome this, you need to tell the GC not to move objects while using them. For this you need to use
pin_ptr<int*> pinnedFrameWidth = &frameWidth;
then pass pinnedFrameWidth to GetImageSize. Pin_ptr will be automatically passed int * when passed to the method.
You must be careful when using pin_ptr. Because the GC cannot move the Test instance during collection, the managed heap can become fragmented and ultimately suffer performance degradation. Ideally, output as few objects as possible in the shortest possible time.
There is a short description of pin pointers in this .Net Rocks show.
a source to share