gpt4 book ai didi

c# - 困惑: instance creation of c# class in c++

转载 作者:IT老高 更新时间:2023-10-28 22:21:31 25 4
gpt4 key购买 nike

假设 someClass 是一个用 C# 定义的类,带有一些方法 int doSomething(void),并且为简单起见,提供一个不带参数的构造函数。然后,在 C# 中,必须在 gc 堆上创建实例:

someClass c;                   // legit, but only a null pointer in C#
// c->doSomething() // would not even compile.
c = new someClass(); // now it points to an instance of someclass.
int i = c->doSomething();

现在,如果someClass被编译成一些.Net库,你也可以在C++/CLI中使用它:

someClass^ cpp_gcpointer = gcnew someClass();
int i = cpp_gcpointer->doSomething();

就这么简单!漂亮!这当然是假设对 .Net 库的引用已添加到项目中,并且已做出相应的 using 声明。

据我了解,这是与前面的 C# 示例完全相同的 C++/CLI 示例(浓缩为一行,这不是我感兴趣的重点)。正确的? (对不起,我是这个话题的新手)

然而,在 C++ 中,也

someClass cpp_cauto;              // in C++ declaration implies instantiation
int i = cpp_cauto.doSomething();

是有效的语法。出于好奇,我今天尝试了这个。一位同事看着我的肩膀,愿意打赌它甚至不会编译。他会输掉赌注。 (这仍然是 C# 程序集中的类)。实际上,它也产生与前面示例中的代码相同的结果 i

也很漂亮,但是 - 嗯 - 它到底是什么,这里创造了什么?我的第一个疯狂猜测是,在我背后,.Net 在 gc 堆上动态创建一个实例,而 cpp_auto 是该对象的某种包装器,其语法行为类似于类 someClass< 的实例。但后来我找到了这个页面

http://msdn.microsoft.com/en-us/library/ms379617%28v=vs.80%29.aspx#vs05cplus_topic2

此页面似乎告诉我,(至少,如果 someClass 是 C++ 类)cpp_auto 实际上是在堆栈上创建的,据我所知,这与您得到的行为相同在经典 C++ 中。还有一些你不能在 C# 中做的事情(你不能,可以吗?)。我想知道的是:来自 C# 程序集的实例是否也在堆栈上创建?您可以在 C++ 中使用无法在 C# 中创建的堆栈上的类实例生成 .Net 二进制文件吗?这甚至可能会给您带来性能提升:-) 吗?

亲切的问候,

托马斯

最佳答案

link you referenced详细解释:

C++/CLI allows you to employ stack semantics with reference types. What this means is that you can introduce a reference type using the syntax reserved for allocating objects on the stack. The compiler will take care of providing you the semantics that you would expect from C++, and under the covers meet the requirements of the CLR by actually allocating the object on the managed heap.

基本上,它仍在对托管堆上的引用类型进行处理,但是当它超出您的范围时,会自动在 IDisposable 实现上调用 Dispose() .

然而,对象实例仍然通过 gcnew 有效分配(放置在托管堆上)并由垃圾收集器收集。这也有详细解释:

When d goes out of scope, its Dispose method will be called to allow its resources to be released. Again, since the object is actually allocated from the managed heap, the garbage collector will take care of freeing it in its own time.

基本上,这一切都由编译器处理,以使代码看起来和工作起来像标准 C++ 堆栈分配的类,但它实际上只是一个编译器技巧。生成的 IL 代码仍在进行托管堆分配。

关于c# - 困惑: instance creation of c# class in c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8247862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com