'Cython: pass data as user-defined type

I have a C++ SDK that I'm trying to write a Python wrapper for. In the header, there's a class Packet that's mentioned but never expounded upon, and there's also a Sensor class that is. This latter class has a method that takes an object of the former, like

...
class Packet
...
namespace space {
    class Sensor {
    ...
    void processPacket(Packet& packet);
    ...
    }
}

My question is how do I get Python data into this processPacket method? I don't have access to the SDK source code. So far, I've got

from cython.operator import dereference


cdef extern from "Sensor.hpp":
    cdef cppclass Packet:
        pass


cdef extern from "Sensor.hpp" namespace "space":
    cdef cppclass Sensor:
        Sensor() except +
        ...
        void processPacket(Packet &packet)


cdef class PyPacket:
    cdef Packet *thisptr


cdef class PySensor:
    cdef Sensor *thisptr
    ...
    def process_packet(self, PyPacket packet):
        self.thisptr.processPacket(dereference(packet.thisptr))

It compiles, but when I try to pass data into it with

sensor = Sensor(...)
data = b'...'
wrapped_data = PyPacket(data)
sensor.process_packet(wrapped_data)

I get a segmentation fault.

Update

By changing the method to

    def process_packet(self, PyPacket packet):
        self.thisptr.processPcapPacket(<PcapPacket&> packet)

it seems to be working. *fingers crossed*



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source