Creating swig wrapper for C++ (pointers) to python

落花浮王杯 提交于 2019-12-01 20:22:44

If I've understood this correctly the problem you're facing isn't that they're pointers, it's that they're potentially unbounded arrays.

You can warp an unbounded C array using carrays.i and the "%array_class" macro, e.g.:

%module packet
%include "stdint.i"

%{
    #include "packet.h"
%}

%include "carrays.i"
%array_class(uint8_t, buffer);

%include "packet.h"

Would then allow you to in Python write something like:

a = packet.buffer(10000000) 
p = packet.CPacketBuffer(a.cast(), 10000000)

Note that you'll need to ensure the life of the buffer is sufficient - if the Python object gets released without the C++ code being aware you'll end up with undefined behaviour.

You can convert uint8_t* pointers (unbounded arrays) to buffer instances in Python using the frompointer methods that the %array_class macro also creates, e.g.:

r = packet.GetBuffer()
buf = packet.buffer_frompointer(r)

You can add additional Python code to automate/hide most of the conversion between buffers if desired, or use MemoryViews to integrate tighter with Python on the C API side.

In general though since this is C++ I'd suggest using std::vector for this - it's much nicer to use on the Python side than the unbounded arrays and the cost is minimal for the safety and simplicity it gives you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!