【问题标题】:How new keyword works in c#c#中new关键字的工作原理
【发布时间】:2009-03-07 09:15:50
【问题描述】:

有一个类被编译成dll

//HeaderFile.h 
//version 1.0
class __declspec(dllexport) A {
    int variable;
//member functions omitted for clarity
};

//implementation file omitted for clarity

您从编译成的 dll 构建一个使用上述类的 exe

#include "HeaderFile.h"
int main() {
    A *obj = new A();
    obj->CallSomeFuncOnObj();

    //
    //whatever
    //
}

到目前为止,您的程序运行良好。但是现在您重新编译您的 dll 使用以下代码

//HeaderFile.h
//version 2.0
class __declspec(dllexport) A {
    int variable;
    int anotherVariable;
//member functions omitted for clarity
};

//implementation file omitted for clarity

并且您不要重新编译您的 exe,而是开始使用旧 exe 中重新编译的 dll。现在会发生的是,您的 exe 具有将分配内存 = sizeof(A 类 1.0 版)的代码,但您的新 dll 中的构造函数的代码假定它正在传递一个内存块 = sizeof(A 类 2.0 版)。两者之间有一个整数的价值大小差异 - 一个不可预测的秘诀。

一个类似的例子出现在一本好书的第一章 - Don Box 的 Essential COM。现在来回答这个问题。在 c#(或任何其他 .Net 语言)的类似情况下会发生什么?

【问题讨论】:

    标签: c# .net c++


    【解决方案1】:

    在 COM 中,您的 DLL 实现了一个对象工厂:DLL 自己创建对象以避免此类“同步”问题。在 .NET 中,CLR 根据从实现类型的 DLL 中提取的类型知识来实例化对象。在这两种情况下,都避免了您提到的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多