I have a array T*
which is created like the following
T* array = new T[len];
// Some initialization codes
We know we can delete the array like
delete [] array;
However, I am writing a Rust FFI program with C++. I have sent this array
pointer to the Rust part of my code, and I want to delete the code now.
So I can implement a function ffi_delete_array_of_T
on the C++ part, and the Rust part code will call the function through FFI, attached with the argument array
.
void ffi_delete_array_of_T(void * arr) {
delete [] reinterpret_cast<T *>(arr);
}
However, I already have a function which can delete single element of T
.
void ffi_delete_pointer_of_T(void * arr) {
delete reinterpret_cast<T *>(arr);
}
These two functions are so similar that I wonder if I can combined them into one, so I don't need to write two copy.
void ffi_delete_whatever_of_T(void * arr, bool is_array) {
if (is_array)
delete [] reinterpret_cast<T *>(arr);
else
delete reinterpret_cast<T *>(arr);
}
However, I still think the above codes redundant. I wonder if I only give ffi_delete_pointer_of_T
, is it possible the Rust do some magic, and have ffi_delete_array_of_T
for me?
To the best of my knowledge, it is not possible. C++ can delete []
a array without hint of length, because it has already stored the length of array
somewhere when array
is allocated. However, the Rust part don't know the actual length of this array
.
However, I still wonder if there are some other ways to do that?