我对 swig 非常陌生,我正在尝试创建一个 swig 包装器,以便在 python 中使用一些 C++ 文件。我有以下 C++ 课程。
以下是我尝试转换的代码片段:
/*packet_buffer.h*/
class CPacketBuffer {
public:
// construct based on given buffer, data is not copied
CPacketBuffer(uint8_t* data, uint32_t length) {
mpBuffer = data;
mLength = length;
mHead = 0;
mTail = length;
}
uint8_t* GetBuffer() {
return (mpBuffer + mHead);
}
void Add(const uint8_t* data, uint32_t length) {
if ((mTail + length) > mLength) {
length = (mLength - mTail);
}
//....
}
我今天一整天都在尝试使用 swig 文档的帮助编写一个 example.i 文件,该文件将接受指向 typedefs(uint8_t *) 的指针,但我没有成功。
以下是我尝试过的 packet_buffer.i 文件,但不起作用。
%module packet_buffer
%include typemaps.i
%apply unsigned char* {uint8_t*};
%apply unit8_t *INPUT {uint8_t *data};
%{
#define SWIG_FILE_WITH_INIT
#include "../include/packet_buffer.h"
%}
%include "../include/packet_buffer.h"
- 如何为采用 typedef 指针的成员函数编写 swig 代码?
- 我可以编写一个可在整个代码中使用的通用 %apply 还是必须为每个 INPUT、OUTPUT 参数编写具体信息?
如果我正确理解了这一点,那么您面临的问题不是它们是指针,而是它们可能是无界数组。
You can 扭曲无界 C 数组使用 carrays.i 和“%array_class”宏,例如:
%module packet
%include "stdint.i"
%{
#include "packet.h"
%}
%include "carrays.i"
%array_class(uint8_t, buffer);
%include "packet.h"
然后允许你在 Python 中编写如下内容:
a = packet.buffer(10000000)
p = packet.CPacketBuffer(a.cast(), 10000000)
请注意,您需要确保缓冲区的寿命足够 - 如果 Python 对象在 C++ 代码不知道的情况下被释放,您将最终得到未定义的行为。
你可以转换uint8_t*
使用以下命令在 Python 中指向缓冲区实例的指针(无界数组)frompointer
的方法%array_class
宏还创建,例如:
r = packet.GetBuffer()
buf = packet.buffer_frompointer(r)
You can 添加额外的 Python 代码如果需要,可以自动/隐藏缓冲区之间的大部分转换,或者使用内存视图在 C API 端与 Python 更紧密地集成。
一般来说,因为这是 C++ 我建议使用std::vector
为此,在 Python 端使用它比无界数组要好得多,而且它为您提供的安全性和简单性的成本是最低的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)