我有一个 C 程序调用一个大型 C++ 库的 C++ 包装器。 C++ 库的功能之一是提供一些预测,而这些预测将在 C 中使用。我想知道我应该在哪里
free
或 delete
内存。这是一些示例代码。
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
I
new
C++ 代码中的初始变量classValues
,然而我release
std::unique_ptr
作为C++ run_model
函数的返回值。我的理解是,当我 release
内存到 C 时,C 代码负责 free
内存。是这样吗?我是否应该有一个 C++ 方法来删除 predictions
变量(从 C 中),就像我有一个 C++ 方法来删除 model_struct
变量一样?我对如何最好地管理这里的内存感到困惑。我被建议不要在 C++ 中使用malloc
(或calloc
),但由于我将值传递回 C,也许这是一个更好的选择......?我不确定。
最简单的解决方案是将C++调用分成两个调用。第一个确定所需缓冲区的大小。然后就可以在C部分分配内存了。在第二次调用中,数据被复制到这个缓冲区中。这样内存管理完全保留在 C 部分。
或者,C++接口必须提供清除内存的函数。当要释放内存时,C 代码会调用它。通常的规则适用:
malloc
-> free
new
-> delete
new[]
-> delete[]
如果我没看错,您目前正在实施第二种方法,但使用不正确
new[]
-> delete
!