在 cli 类中声明本机类型?
我
public ref class Test
在这个类中有一个,我有:
int frameWidth;
int frameHeight;
int frameStride;
当我尝试编译这个时,我收到错误:
error C2664: 'GetImageSize' : cannot convert parameter 1 from 'cli::interior_ptr<Type>' to 'int *'
GetImageSize 是一个本机函数,只有当我将上面 3 个整数的声明移动到类外部或块内部时它才起作用调用 GetImageSize。
我该如何解决这个问题?
这 3 个整数需要被类中的多个函数访问,现在我让它工作了,因为我将它们移到了类之外,但我认为这不是正确的做法,因为它们已经成为全局的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据这篇文章,您看到这一点的原因是因为整数位于引用类内,垃圾收集器可以随意在堆中移动整数,整数的地址可能会更改并且您不会被告知。
为了克服这个问题,您需要告诉 GC 在使用对象时不要移动它们。 为此,您需要使用
pinnedFrameWidth,然后将其传递到 GetImageSize。 当传入方法时,pin_ptr 将自动转换为 int*。
使用 pin_ptr 时需要小心。 由于 GC 无法在收集期间移动 Test 类的实例,因此托管堆可能会变得碎片化,最终性能会受到影响。 理想情况下,在尽可能短的时间内固定尽可能少的物体。
这个 .Net Rocks 节目中对 pin 指针进行了简要讨论。
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
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.