如何确定性地处置C#中的托管C ++ / CLI对象? [英] How can I deterministically dispose of a managed C++/CLI object from C#?

查看:54
本文介绍了如何确定性地处置C#中的托管C ++ / CLI对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++ / CLI程序集中有一个托管对象。作为C ++ / CLI,它通过其析构函数实现了Disposable模式(是的,我知道它与标准C ++析构函数不同)。从C ++ / CLI,我可以简单地删除对象。但是,我将此对象用作C#类中的成员变量。

I have a managed object in a C++/CLI assembly. Being C++/CLI, it implements the Disposable pattern through its "destructor" (yes, I'm aware it's not the same as a standard C++ destructor). From C++/CLI, I would simply delete the object. However, I am using this object as a member variable in a C# class.

从我的C#类中,我想调用Dispose()的等效项。当我完成使用C ++ / CLI对象上的方法时。由于它是(并且必须是)该类的成员变量,因此不可能使用using()块。据我所知,没有公开的方法可以直接,确定性地使用C ++ / CLI以外的语言来处理资源。我该如何完成呢?

From my C# class, then, I would like to call the equivalent of the Dispose() method on the C++/CLI object when I am finished using it. Since it is (and must be) a member variable of the class, utilizing a using() block is out of the question. As far as I can tell, there is no exposed method for direct, deterministic disposal of resources from a language other than C++/CLI. How can I accomplish this?

推荐答案

类似于C ++ / CLI析构函数的语法会自动实现 IDisposable ,但是这样做的方式与C#的显式接口实现类似。这意味着您必须转换为 IDisposable 来访问 Dispose 方法:

The C++/CLI destructor-like syntax automatically implements IDisposable, but it does so in a manner similar to C#'s explicit interface implementation. This means you'll have to cast to IDisposable to access the Dispose method:

((IDisposable)obj).Dispose();

这篇关于如何确定性地处置C#中的托管C ++ / CLI对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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