There is libx.so that exports 2 functions and a struct ,
typedef struct Tag { int num; char *name; }Tag; Tag *create(int n, char *n) { Tag *t = malloc(sizeof(Tag)); t->num = n; t->name = n; return t; } void use(Tag *t) { printf("%d, %s\n", t->num, t->name); }
I want to call create in Python and then save the Tag *res returned by create , later I will call use and pass the Tag *res stored before use , here it is (just for demonstration):
>>>libx = ctypes.CDLL("./libx.so") >>>res = libx.create(c_int(1), c_char_p("a")) >>>libx.use(res)
The above code might be wrong, just to demonstrate what I want to do.
And my problem is that, how can I save the result returned by create ? Since it returns a pointer to a custom struct , and I don't want to construct a struct Tag in Python, would the c_void_p trick?
UPDATE
From @David's answer, I still don't quite understand one thing:
the pointer ( c_char_p("a") ) is valid only for a while call create . As soon as create is returned, this pointer is no longer valid.
And I assign c_char_p("a") t->name to create , when the create call ends, is t->name dangling pointer? Since, according to the quoted words, this pointer no longer acts after create . Why is c_char_p("a") no longer valid?