1

Swig's manual is kinda confusing to me. I am wrapping my C library to python so that I can test my C code in python. Now I want to know how I can access the C pointer address in Python, for example, this is the code I have

typedef struct _buffer_t {
char buf[1024];
char *next_ptr;
} buffer_t;



void parse_buffer(buffer_t * buf_p) {
    buf_p -> next_ptr ++;
}

What I wanted to do is below, in C code

buffer_t my_buf;
my_buf.next_ptr = my_buf.buf;
parse_buffer(&my_buf);
expect_equal(&(my_buf.buf)+1, my_buf.next_ptr);

How do I do the same thing in Python? After import the SWIG wrapped module, I have the buffer_t class in python.

1 Answer 1

1

The problem is that SWIG is trying to wrap the buffer as a String in Python, which is not just a pointer. The synthesised assignment for next_ptr will allocate memory and make a string copy, not just do a pointer assignment. You can work around this in several ways.

The simplest is to use %extend to add a "reset buffer" method in Python:

%extend {
  void resetPtr() {
    $self->next_ptr=$self->buf;
  }
}

which can then be called in Python to make the assignment you want.

Alternatively if you want to force the buffer to be treated as just another pointer you could force SWIG to treat both members as void* instead of char* and char[]. I had hoped that would be as simple as a %apply per type, but it seems not to work correctly for memberin and memberout in my testing:

%apply void * { char *next };
%apply void * { char buf[ANY] };

Given that the memberin/memberout typemaps are critical to making this work I think %extend is by far the cleanest solution.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for point out the %extend option. It works, I also used it for getting the pointer address out.
A follow up question, I have an function like void my_func(void * ptr); How can I pass in my buf_p->next_ptr to it? I have already used %apply void * {char * next_ptr} to replace the type. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.