tags:

views:

277

answers:

1

I have a

public ref class Test

inside this class, I have:

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 native function and it works only if I move the declaration of the 3 ints above to outside the class or inside the block that calls GetImageSize.

How can I solve this?

Those 3 ints needs to be accessible by more than one function within the class, right now I made it work because I moved them to outside the class, but it's not the right thing to do I believe since they become global...

thanks!

+1  A: 

According to this post, the reason you are seeing this is because the ints are inside a ref class which can be moved around the heap by the garbage collector at will, the address of the ints could change and you wouldn't be told.

To overcome this, you need to tell the GC not to move the objects while you are using them. To do this you need to use

pin_ptr<int*> pinnedFrameWidth = &frameWidth;

then pass pinnedFrameWidth into GetImageSize. The pin_ptr will be automatically cast to int* when passed into the method.

You need to be careful when using pin_ptr. Because the GC can't move the instance of Test class around during a collection, the managed heap can become fragmented and, eventually, performance can suffer. Ideally pin as few objects for the least amount of time possible.

There is a brief discussion of pin pointers in this .Net Rocks show.

Colin Desmond
awesome! thanks!