使用SomeType **作为函数参数的Python SWIG绑定



我找不到任何适用于ffmpeg的Python绑定,所以我决定用SWIG生成一个。生成是快速和容易的(没有定制,只有默认的SWIG接口),但这些问题使用一些函数,如int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options);从libavformat/avformat.h。使用C语言,可以简单地运行:

AVFormatContext *pFormatCtx = NULL;
int status;
status = avformat_open_input(&pFormatCtx, '/path/to/my/file.ext', NULL, NULL);

在Python中我尝试如下:

>>> from ppmpeg import *
>>> av_register_all()
>>> FormatCtx = AVFormatContext()
>>> FormatCtx
<ppmpeg.AVFormatContext; proxy of <Swig Object of type 'struct AVFormatContext *' at 0x173eed0> >
>>> avformat_open_input(FormatCtx, '/path/to/my/file.ext', None, None)
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: in method 'avformat_open_input', argument 1 of type 'AVFormatContext **'

问题是Python没有&等价的。我试图使用cpointer.i和它的pointer_class (%pointer_class(AVFormatContext, new_ctx)),但new_ctx()返回指针,这不是我想要的。%pointer_class(AVFormatContext *, new_ctx)是非法的,会导致语法错误。我将感激任何帮助。谢谢。

编辑:我忘了说我尝试过使用typemaps,但不知道如何为struct编写自定义typemap,文档中只有int或float等基本类型的示例…

这看起来像是一个out参数。这在C中是必要的,因为C只允许一个返回值,而Python允许多个。SWIG允许您将参数标记为OUTPUT或INOUT,以完成您想要的操作。看到这个。

您也可以使用typemap手动完成。typemap允许您指定任意转换。

例如,您可能需要在typemap文档中描述的inargout类型映射。

请注意,由于您使用的是自定义数据类型,因此需要确保声明该结构的头文件包含在生成的.cpp中。如果SWIG不能自动处理这个问题,那么在你的。i

的顶部放一些这样的东西。
// This block gets copied verbatim into the header area of the generated wrapper.
%{
#include "the_required_header.h"
%}

最新更新