Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting Python str to C const char *

i just started some Python Wrapper for a C .dll. And used SWIG for it. I ran into the problem that a C Function from the dll takes a typedef of a const char * as argument. I Wrapped the .h of my C libary as following (the typedef is copied from the header to the interface when trying a lot of stuff to make it work, don't really know if that is necessary):

Added: 
%include "cpointer.i"
%pointer_class(signed char, p_char);

%apply const char * { chararrayiwant }; //not sure if only should be char

Old Code:
%include "typemaps.i"
%include "windows.i"

%module somemodule
%{  #include "someheader.h"
    typedef char chararrayiwant[33];
%}

%include "someheader.h"
typedef char  chararrayiwant[33];

When i try to Execute it in my Python file like this:

import mylib as d
...
key = b"somereallylongserialkey"  # type: str
p = ctypes.c_char_p(key)
x = d.myfunc(p, 1, None, None)

i run into following error:

 x = d.myfunc(p, 1, None, None)
TypeError: in method 'myfunc', argument 1 of type 'chararrayiwant const *'

I tried this for 2 days now and have not found any solution to make it work..

Thanks in advance!

P.S: does not work with the added lines

like image 627
SGURL Avatar asked Dec 07 '25 05:12

SGURL


1 Answers

I guess You should pass a pointer to string to myfunc not a string. Try:

p2 = ctypes.addressof(p);
x = d.myfunc(p2, 1, None, None);

The first function argument has the type constchararrayiwant * which is char [33] * which is char**.

like image 107
KamilCuk Avatar answered Dec 08 '25 17:12

KamilCuk