【问题标题】:Method to Force C++ Class to be Destructed After Interop Call from C#从 C# 进行互操作调用后强制破坏 C++ 类的方法
【发布时间】:2023-03-03 16:59:01
【问题描述】:

我有以下包装器来提供从 C# 访问我的 C++ DLL 的权限

#include "Stdafx.h"
#include "Config.h"
#include "Utils.h"
#include "LogicCompiler.h"

extern "C" {
   LIBRARY_EXPORT void GenerateTables(
      const char* version, 
      const char* baseDir, 
      const char** fileList);
} // end extern "C"

void GenerateTables(
   const char* version,
   const char* baseDir, 
   const char** fileList)
{
   std::string strVersion(version);
   std::string strBaseDir(baseDir);
   std::vector<std::string> vFileList = Utils::CharArrayToVector(fileList);
   LogicCompiler* compiler = new LogicCompiler(strVersion, strBaseDir, vFileList);
   compiler->m_PreProcessor->GenerateTables();
}

这个调用运行良好,GenerateTables 完成了它的工作。问题是 LogicCompiler* compiler 的析构函数永远不会被调用。在那里执行一些操作(清理等)。为了处理compiler 对象并尝试启动析构函数,我在上面显示的GenerateTables() 方法的末尾添加了free(compiler);,但这也不会调用析构函数。

如何强制编译器对象被正确释放,从而调用类析构函数?

感谢您的宝贵时间。


编辑。我尝试的第一件事是使用delete compiler;,但这没有编译。

【问题讨论】:

  • 您当然必须使用delete 运算符。或者干脆让编译器使用 LogicCompiler compiler(...);
  • 切勿将new/deletemalloc()/free() 混合使用,因为这是未定义的行为
  • @HansPassant,我无法使用delete compiler; 编译代码。第二句是什么意思?
  • delete compiler; 的编译错误是什么?
  • 我不会猜测“未编译”。正确记录您的问题。

标签: c# c++ dll interop destructor


【解决方案1】:

永远不会newfree()malloc()delete一起使用,因为那是通往编程地狱的道路。

因此,既然你用new 分配了你的对象,你应该用delete 释放它。使用free() 不会调用对象的析构函数也不会 malloc() 调用其构造函数)

您需要在 C++ 中使用 malloc()/free() 的唯一时间应该是重载 new 运算符,分别是 delete 运算符。即使这样,您也应该使用他们的 STL 对应项(std::malloc()std::free()

【讨论】:

  • 感谢您的建议。我尝试的第一件事是使用delete,但编译器不允许我这样做......
猜你喜欢
  • 2023-03-25
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 2020-03-05
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多