Declare native types inside a cli class?

旧时模样 提交于 2020-01-14 05:39:41

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/893317/declare-native-types-inside-a-cli-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!