I've started to play around with SWIG, so that I can use C libraries in Python. I have this piece of code where I'm passing a Python String into a C function that expects a "void *"
example.h:
char test(void *buf);
example.c:
char test(void *buf) {
char *c = (char*)buf;
return *c;
}
Python:
import example
buf = "hello"
example.test(buf)
When I run it, I get the following error:
TypeError: in method 'test', argument 1 of type 'void *'
However, when I change the "void*" parameter to "char*", it seems to work. I'm a little confused as I thought "void*" matches any kind of pointer. Anyways, I dug around and came across the ctypes library and casted it to a c_void_p (Python: converting strings for use with ctypes.c_void_p()). That didn't seem to work for me.
As a work around I made a wrapper in my swig file:
/* File: example.i */
%module example
%include typemaps.i
%{
#include "example.h"
%}
%include "example.h"
%inline %{
char test_wrapper(char *buf) {
void *voidBuf = (void*)buf;
return test(voidBuf);
}
%}
This seems to work. However, I was wondering if someone could provide an explanation as to why the ctypes approach didn't work. If I was completely off the mark with the ctypes approach, is there a more appropriate way than creating an inline wrapper?
Thanks guys!