【发布时间】: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/delete与malloc()/free()混合使用,因为这是未定义的行为 -
@HansPassant,我无法使用
delete compiler;编译代码。第二句是什么意思? -
delete compiler;的编译错误是什么? -
我不会猜测“未编译”。正确记录您的问题。
标签: c# c++ dll interop destructor