我有一个 C 程序,它调用一个大型 C++ 库的 C++ 包装器。 C++ 库的功能之一是提供一些预测,这些预测将在 C 中使用。我想知道应该在哪里释放
或删除
内存。这是一些示例代码。
cpp_wrapper.cpp
#include "cpp_wrapper.h"
uint8_t * run_model(struct_with_model model_struct, const double * input_data) {
// the model_struct is new'd in C++ in an earlier method
// I have a method to convert the input data to std::vector for use in C++ code
std::vector<double> data = get_data(input_data);
model_struct->model->LoadData(data);
model_struct->model->run();
std::vector<uint8_t> predictions = model_struct->model->GetPredictions();
std::unique_ptr<uint8_t[]> classValues (new uint8_t[predictions.size()]);
memcpy(classValues.get(), predictions.data(), sizeof(uint8_t) * predictions.size());
model_struct->model->ClearData(); //clears data from model for future runs, if necessary
return classValues.release()
}
void model_delete(model_struct) {
// method to delete the model_struct when necessary
delete model_struct;
}
我有一个 cpp_wrapper.h
头文件,它声明这些函数并根据需要调用 extern C
。在C端,c_code.c
:
#include "cpp_wrapper.h"
/*
There's a bunch of code here for ingesting data, initializing the model_struct, etc
*/
uint8_t * predictions = run_model(model_struct, input_data);
// Do stuff with predictions, as necessary
model_delete(model_struct);
free(predictions); // HERE is the question
我在 C++ 代码中new
初始变量classValues
,但是我释放
std::unique_ptr
作为 C++ run_model
函数的返回。我的理解是,当我释放
内存给C时,C代码负责释放
内存。是这样吗?我是否应该有一个 C++ 方法来删除 predictions
变量(从 C),就像我有一个 C++ 方法来删除 model_struct
变量一样?我对如何最好地管理这里的内存感到困惑。建议我不要在 C++ 中使用 malloc
(或 calloc
),但由于我将值传递回 C,也许这是一个更好的选择...?我不确定。
最佳答案
最简单的解决方案是将 C++ 调用分为两个调用。第一个确定需要的缓冲区有多大。然后就可以在C部分分配内存了。在第二次调用中,数据被复制到该缓冲区中。这样内存管理就完全保留在C部分了。
或者,C++ 接口(interface)必须提供清除内存的函数。当要释放内存时,C 代码会调用此函数。通常的规则适用:
malloc
->free
新建
->删除
新建[]
->删除[]
如果我没看错,那么您目前正在实现第二种方法,但错误地使用了 new[]
-> delete
!
关于c++ - 从 C++ 到 C 释放 unique_ptr 时如何避免内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75902106/