ctypes issue with freeing memory after reintepret_cast

  c++, ctypes, memory-management, python

I am using ctypes to create C++ bindings, and the following code, which is wrapped in C, baffles me. I have a separate header .hpp file where functions and a class are declared, and a main.py file, from which i call said functions. In python i convert a list into an array of pointers, and pass it to the function by doing something like (based on How do I convert a Python list into a C array by using ctypes?)

    pyarr = [1, 2, 3, 5]
    arr = (ctypes.c_int * len(pyarr))(*pyarr)

    Class_ctor_wrapper = ccd_lib.CreateInstanceOfClass
    Class_ctor_wrapper.restype = ctypes.c_void_p
    ptr = ctypes.c_void_p(Class_ctor_wrapper())

    value = ccd_lib.CallMemberTest(ptr, 4, arr)
int class::test(int arr_len, void *arr) {
        
        int* intarr = reinterpret_cast<int*>(arr); 
        int sum = 0;
        for (int id = 0; id < arr_len; id++){
            sum += intarr[id];
        }
        free(intarr); // doesn't work
        return sum;
    }

int CallMemberTest(void *ptr, int arr_len, void *arr)
    {

        {
            class* ref = reinterpret_cast<class*>(ptr);
            int res = ref->test(arr_len, arr);
            free(ref); // works
            return res;
        }
        catch(...)
        {
            return -1; //assuming -1 is an error condition.
        }
    }

I want to make sure I am not allocating extra memory with intarr and ref (maybe this is not an issue? Are they automatically deleted?), so i want to free (or delete, however that didn’t seem to work) them, and for some reason it works for one, but not the other. Can someone explain this?

Source: Windows Questions C++

LEAVE A COMMENT