.NET删除固定的分配缓冲区 [英] .NET deletes pinned allocated buffer

查看:70
本文介绍了.NET删除固定的分配缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来分配缓冲区

I have the following code to allocate buffer

uns16 m_rawBuffer = new uns16[m_rawBufferSize];
pin_ptr<uns16> ptrAcqBuffer = m_rawBuffer;

尽管它不时是pin_ptr,GC还是会修改ptrAcqBuffer.

Although it is pin_ptr from time to time GC modifies ptrAcqBuffer.

从文档中我看到

固定指针是防止对象移动的内部指针 指向从垃圾收集堆移动.那就是 公用语言不会更改固定指针的值 运行.当您传递托管类的地址时,这是必需的 到非托管功能,以便地址不会更改 在解析非托管函数调用期间意外地.

A pinning pointer is an interior pointer that prevents the object pointed to from moving on the garbage-collected heap. That is, the value of a pinning pointer is not changed by the common language runtime. This is required when you pass the address of a managed class to an unmanaged function so that the address will not change unexpectedly during resolution of the unmanaged function call.

这对我没什么...有人可以解释一下吗? 另外,因为我用"new"创建了m_rawBuffer,所以我需要"pin_ptr"吗?

It doesn't make sesnse to me... Can someone please explain ? Also because I created m_rawBuffer with "new" do I need to "pin_ptr" ?

谢谢.

推荐答案

每当垃圾回收器执行垃圾回收时,它都会移动托管堆上的所有对象.这是其正常操作的一部分.这就是指向托管对象的常规"指针无效的原因,因为垃圾回收器可以随时移动它.

The garbage collector moves all of the objects on the managed heap whenever it does a garbage collection. This is part of its normal operation. This is why a 'regular' pointer to a managed object isn't valid, because it can be moved at any time by the garbage collector.

pin指针将托管堆上的对象标记为别动我!",因此只要pin_ptr对象存在,该指针就保持有效.然后,您可以将pin指针传递给需要常规原始指针的方法,并且指向的对象在pin_ptr对象被销毁之前不会移动.

A pin pointer marks the object on the managed heap as "don't move me!", so the pointer remains valid as long as the pin_ptr object exists. You can then pass the pin pointer to methods that expect a regular raw pointer, and the object that it's pointing at won't move until the pin_ptr object is destroyed.

所有这些都与托管堆有关.假设您显示的代码片段是C ++/CLI代码,则使用new在常规 unmanaged 堆上分配一个数组.固定不是必需的,它不会自行移动.

All of this has to do with the managed heap. Assuming the code fragment you showed was C++/CLI code, you're using new to allocate an array on the regular unmanaged heap. Pinning is not necessary, it will not move on its own.

如果您已完成array<UInt16>^ buffer = gcnew array<UInt16>(m_rawBufferSize);,则需要使用图钉.

If you had done array<UInt16>^ buffer = gcnew array<UInt16>(m_rawBufferSize);, then you would need the pin.

... GC有时会修改ptrAcqBuffer.

...from time to time GC modifies ptrAcqBuffer.

我不确定那里发生了什么.我不确定pin_ptr在尝试首先提供它不在托管堆上的内容时会做什么,因此可能会出现奇怪的行为.由于无论如何您都不需要别针,所以我不用担心.

I'm not sure what's going on there. I'm not sure what pin_ptr does when you try to give it something that isn't on the managed heap in the first place, so weird behavior is probably to be expected. Since you don't need the pin anyway, I wouldn't worry about it.

这篇关于.NET删除固定的分配缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆