How to fix segmentation error when working with Python Ctypes and C ++?

Let's say I have the following two function signatures in C ++:

BYTE* init( BYTE* Options, BYTE* Buffer )

and

int next( BYTE* interface, BYTE* Buffer )

The idea is that I first initialize the class Interfacein C ++ and then call the function nextfrom Python with reference to this class.

The first function returns a pointer BYTEto the interface through:

Interface*  interface;
// initialize stuff
return((BYTE*) interface);

I call it in Python as follows:

class Foo:
  def init(self, data):
    # left out: setting options_ptr
    buf = (c_ubyte * len(data.bytes)).from_buffer_copy(data.bytes)
    init_fun = getattr(self.dll, '?init@@YAPAEPAE0HH@Z')
    init_fun.restype = POINTER(c_ubyte)
    self.interface_ptr = init_fun(options_ptr, buf)
    # this works fine!

  def next(self, data):
    # create buf from other data
    buf = (c_ubyte * len(data.bytes)).from_buffer_copy(data.bytes)
    next_fun = getattr(self.dll, '?next@@YAHPAE0HN@Z')
    ret = next_fun(self.interface_ptr, buf)
    # I randomly get segmentation faults here

I call it from the outside using, for example:

foo = Foo()
foo.init(some_data)
foo.next(some_other_data)
# ...
foo.next(some_additional_data)

Now when I run it, I get segmentation errors:

[1]    24712 segmentation fault  python -u test.py

Sometimes this happens after the first call .next(), sometimes it happens after the eleventh call .next()-totally in random order.

There is C ++ test code for the API that works something like this:

BYTE Buffer[500000];
UTIN BufSize=0;
BYTE* Interface;

# not shown here: fill buffer with something
Interface = init(Buffer);
while(true) {
    # not shown here: fill buffer with other data
    int ret = next(Interface, Buffer);
}

, , , : ​​ ? ( VS2012), :

, , . :

data BitString. , , ++ ? Python, ?

, , Ctypes? , DLL API .


: buf , . self._buf, , :

+4
1

, , :

  • Ctypes Python C, Python , () , C .

    , . self._buf.

  • C , . C - , , . Ctypes :

    c_char_p, c_wchar_p c_void_p , , (, , Python ).

    , , . , ctypes create_string_buffer(), . ( ) raw; NUL terminated, value:

    , - :

    self._buf = create_string_buffer(500000)
    self._buf.value = startdata.bytes
  • Python, , , , . , .next() :
    self._buf.value = nextdata.bytes

.

+3

All Articles