我找不到任何可用于ffmpeg的Python绑定,所以我决定用SWIG生成一个绑定。生成是快速而简单的(没有定制,只是默认的SWIG接口),但是使用libavformat/avformat.h中的int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options);
等函数是个问题。使用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)
是非法的,并给出语法错误。如果有任何帮助,我将不胜感激。谢谢。编辑:
我忘了提我试过使用类型映射,但不知道如何为结构编写自定义类型映射,文档中只有一些基本类型的示例,如int或float。。。
最佳答案
看起来这是个out参数。这在C中是必要的,因为C只允许一个返回值,而Python允许多个返回值。SWIG允许您将参数标记为输出或INOUT,以实现您想要的功能。见this。
您还可以使用类型映射手动执行此操作。类型映射允许您指定任意转换。
例如,您可能需要in
和argout
类型映射,如typemap docs中所述。
注意,由于您使用的是自定义数据类型,因此需要确保声明结构的头包含在生成的.cpp中。如果SWIG没有自动处理这个问题,那么在你的顶部放一个这样的东西
// This block gets copied verbatim into the header area of the generated wrapper.
%{
#include "the_required_header.h"
%}
关于python - 使用SomeType **作为函数参数的Python SWIG绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16343165/