SWIG - garbage collection using% newobject

In my C code, I have the following structure:

typedef struct my_structure{
    char* str1;
    char* str2;
}MyStruct;

And a function that returns a MyStruct pointer:

MyStruct* foo();

Inside foo, I allocated memory for MyStruct, str1 and str2, as shown below:

MyStruct* obj = malloc(sizeof(MyStruct));

obj.str1 = malloc(256);
obj.str2 = malloc(256);

I want to call foo from python, java, C # and PHP, and I don't want to have a memory leak in this process.

I'm not sure what I am writing:

%newobject foo;
MyStruct* foo();

ensures that the garbage collector frees memory for both the structure and the lines inside it.

I did not want the calling box to free memory for str1 and str2, as I was looking for an automatic way to free memory. Is it possible?

Is it necessary to use "new information" in this case?

I would really appreciate if you would give me an example showing the best way to accomplish this.

Thank!

+3
source share
1

typemap(newfree) , %newobject, , char * Python, . , %extend , SWIG C, :

%newobject foo;

%extend MyStruct {
    ~MyStruct() {
       free($self->str1);
       free($self->str2);
    }
}

, . , SWIG, , .

+3

Source: https://habr.com/ru/post/1783047/


All Articles