0

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?

calvin
  • 2,125
  • 2
  • 21
  • 38
  • 3
    I feel the first version with 2 functions for 2 different tasks is the most "Rusty". – cafce25 Jan 04 '23 at 04:44
  • 3
    Your second version is just plain weird and ill-advised. Having specialized functions, akin to `delete` vs. `delete[]`, is far more conventional. – tadman Jan 04 '23 at 04:46
  • Is there any way of exposing allocator and deallocator pairs of functions, regardless of if the deallocators are, in many cases, internally the same? It's a lot better to think in terms of `alloc_X()` and `free_X()` than it is in terms of `alloc_X()` and then remembering which deallocator to use. Make it *stupidly* obvious what the correct pairing is, because we all have stupid days. – tadman Jan 04 '23 at 05:00
  • @tadman You also need to run the destructor. – Chayim Friedman Jan 04 '23 at 05:32
  • @ChayimFriedman The FFI interface should perform that operation in the `free` side of things. It's C++ exposed with C naming conventions, but it's still C++. – tadman Jan 04 '23 at 15:35

0 Answers0