检查 .NET 句柄的值 ^
这是我的情况:
我在 C++/CLI 层中有 .NET 包装对象,其中包含指向非托管 C++ 对象的指针。我已经实现了终结器,以便它删除垃圾收集时包装对象指向的非托管内存,并将指针设置为 null。
问题在这里:
我正在观察 .NET 包装对象的终结器,它被调用两次并尝试两次删除相同的内存,这表明我以某种方式创建了 2 个 .NET 包装对象超出范围,并且在我仍然期望包装器对象在范围内时被垃圾收集(这些包装器对象被传递到 VB.NET 应用程序)。
这是我的问题:
我是否可以检查句柄值,以便我可以确认包装器对象的创建位置(复制或其他)?目前我正在查看句柄值 (EG - 0x0014fe80),但我看到了创建对象、添加到集合和删除对象时的 3 个不同值。所以我不确定 GC 是否只是在移动东西并且这是同一个对象,或者我是否实际上看到 3 个不同的对象引用相同的非托管内存。如果可能的话,我想解决重复的对象副本,但我知道我可能想要实现某种智能指针,这样就不会发生这种情况。
谢谢, 伊恩
Here's my situation:
I have .NET wrapper-objects in a C++/CLI layer that hold pointers to unmanaged C++ objects. I've implemented the finalizer so that it deletes the unmanaged memory pointed to by the wrapper-object on garbage-collection and sets the pointer to null.
Here's the problem:
I'm watching the finalizer for the .NET wrapper-object and it gets called twice and tries to delete the same memory twice, indicating that I have somehow created 2 .NET wrapper objects that go out-of-scope, and are garbage collected while I'm still expecting the wrapper object to be in scope (these wrapper objects are getting passed to a VB.NET application).
Here's my question:
Is there anyway for me to check the handle value so that I can confirm where the wrapper objects are getting created (copied or whatever)? Currently I'm looking at the handle values (EG - 0x0014fe80), but I see 3 different values for when the object is created, added to a collection, and deleted. So I'm not sure if the GC is just moving stuff around and this is the same object, or if I'm actually seeing 3 different objects that reference the same unmanaged memory. I would like to resolve the duplicate object copies if possible, but I understand that I will probably want to implement some sort of smart pointer so that this doesn't happen.
Thanks,
Ian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看这个问题
这里是一个
scoped_ptr
的实现,它是不可复制的,并且具有非托管的自动释放机制对象,作者:@Ben VoigtTake a look at this question
Here is an implementation of a
scoped_ptr
that is noncopyable and has an auto-release mechanism for unmanaged objects, by @Ben Voigt是的,我最终将 auto_ptr 类修改为共享指针,以确保非托管内存仅通过智能指针终结器删除一次。我假设我做了与所有其他实现类似的事情;我在 auto_ptr 模板类中创建了一个静态字典,使用本机指针值作为键,每次调用终结器以更新每个项目的计数或删除内存时都会检查该字典。
Yeah, I ended up modifying an auto_ptr class to be a shared pointer to ensure that the unmanaged memory is only deleted once through the smart pointer finalizer. I'm assuming I did something similar to all the other implementations; I created a static dictionary in the auto_ptr template class, using the native pointer value as the key, that is checked every time the finalizer is called to update the count of each item, or delete the memory.