Does Ctypes Structures and POINTERS automatically free the memory when the Python object is deleted?

前端 未结 1 905
长发绾君心
长发绾君心 2021-01-02 08:56

When using Python CTypes there are the Structures, that allow you to clone c-structures on the Python side, and the POINTERS objects that create a sofisticated Python Object

相关标签:
1条回答
  • 2021-01-02 09:23

    The memory is not freed, because Python has no idea if or how it should be freed. Compare these two functions:

    void testfunc1(PIX *pix)
    {
        static char staticBuffer[256] = "static memory";
        pix->text = staticBuffer;
    }
    
    void testfunc2(PIX *pix)
    {
        pix->text = (char *)malloc(32);
        strcpy(pix->text, "dynamic memory");
    }
    

    Used like this:

    pix1, pix2 = PIX(), PIX()
    mylib.testfunc1(ctypes.byref(pix1))
    mylib.testfunc2(ctypes.byref(pix2))
    

    And then at some point, pix1 and pix2 go out of scope. When that happens, nothing happens to the inner pointers—if they pointed to dynamic memory (as is the case here with pix2 but not pix1), you are responsible for freeing it.

    The proper way to solve this problem is, if you allocate dynamic memory in your C code, you should provide a corresponding function that deallocates that memory. For example:

    void freepix(PIX *pix)
    {
        free(pix->text);
    }
    
    
    pix2 = PIX()
    mylib.testfunc2(ctypes.byref(pix2))
    ...
    mylib.freepix(ctypes.byref(pix2))
    
    0 讨论(0)
提交回复
热议问题