问题描述
我有一个
public ref class Test
在这个类中,我有:
int frameWidth;
int frameHeight;
int frameStride;
当我尝试编译这个,我得到错误:
错误C2664:'GetImageSize':无法将参数1从'cli :: interior_ptr< Type>'转换为'int *'
我如何解决这个问题?
这3个int需要被多个函数访问该类,现在我使它的工作,因为我把他们移动到类外,但它不是我相信,因为他们成为全球的正确的事情。
解决方案根据,你看到这个的原因是因为int是在一个ref类中,可以通过垃圾回收器随意移动堆,int的地址可以改变,你不会告诉。
为了克服这个问题,你需要告诉GC不要在使用对象时移动对象。为此,您需要使用
pin_ptr< int *> pinnedFrameWidth =& frameWidth;
然后将pinnedFrameWidth传递给GetImageSize。当传递到方法中时,pin_ptr将自动转换为int *。
使用pin_ptr时需要小心。因为GC在集合期间不能移动Test类的实例,所以受管理的堆可能变得分散,并且最终性能可能受损。
在 .Net Rocks显示。
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.
解决方案 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.
这篇关于在cli类中声明native类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!