user1760653
user1760653

Reputation: 181

Who deletes that memory in python?

I use SWIG for generating wrappers. Therefore I need a function which looks like

%inline %{
// Serializes into a string
void* SerCmd(Class *v, int *length, char *str)
{
    QByteArray ba;
    QDataStream out(&ba, QIODevice::WriteOnly);
    out << *v;
    *length = ba.size();
    str = new char[ba.size()];
    memcpy(str, ba.constData(), ba.size());
    return str;
}
%}

This function is called from python then but who is deleting the memory I allocate with new? Is python doing that for me or how can that be achieved?

Thanks!

Upvotes: 1

Views: 141

Answers (2)

whitebeard
whitebeard

Reputation: 1131

I don't know SWIG either, but since you asked, "Is python doing that for me or how can that be achieved?"

Python garbage collection deletes stuff when it is no longer in scope i.e. no longer has anything pointing to it. However, it cannot delete stuff it is not aware of. These docs may help.

Here is the doc on how memory management works: https://docs.python.org/2/c-api/memory.html

And here are the docs to the gc module to help give you a more control of the process. https://docs.python.org/2/library/gc.html

Upvotes: 0

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

If this doesn't answer your question, I will remove it. But according to the SWIG information found here:

http://www.swig.org/Doc1.3/Library.html#Library_stl_cpp_library

a std::string can be used instead of manually allocating memory. Given this information, this more than likely can be used.

%inline %{
// Serializes into a string
void SerCmd(Class *v, int *length, std::string& str)
{
    QByteArray ba;
    QDataStream out(&ba, QIODevice::WriteOnly);
    out << *v;
    *length = ba.size();
    str.clear();
    str.append(ba.constData(), ba.size());
}
%}

Since you noted that the std::string can contain NULLs, then the proper way to handle it is to use the string::append() function.

http://en.cppreference.com/w/cpp/string/basic_string/append

Please note item 4) in the link above (null characters are perfectly ok). Note that std::string does not determine its size by a null character, unlike C-strings.

Now, to get to this data, use the string::data() function, along with the string::size() function to tell you how much data you have in the string.

Upvotes: 3

Related Questions