【问题标题】:Python SWIG bindings with SomeType ** as function argument使用 SomeType ** 作为函数参数的 Python SWIG 绑定
【发布时间】:2013-05-02 16:29:12
【问题描述】:

我找不到任何适用于 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) 是非法的并给出语法错误。如果有任何帮助,我将不胜感激。谢谢。

编辑: 我忘了提到我尝试使用类型映射,但不知道如何为 struct 编写自定义类型映射,文档中只有基本类型的示例,如 int 或 float...

【问题讨论】:

  • 你是怎么得到avformat的swig接口文件的?还是你自己写的?

标签: python c ffmpeg swig


【解决方案1】:

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

您也可以使用类型映射手动完成。类型图可让您指定任意转换。

例如,您可能需要inargout 类型映射,如typemap docs 中所述。

请注意,由于您使用的是自定义数据类型,因此您需要确保声明结构的标头包含在生成的 .cpp 中。如果 SWIG 没有自动处理这个问题,那么在你的 .i 顶部放置类似这样的内容

// This block gets copied verbatim into the header area of the generated wrapper.

%{
#include "the_required_header.h"
%}

【讨论】:

  • 啊,对不起,我忘了提,我尝试将 typemap 与%apply AVFormatContext *OUTPUT {AVFormatContext **ps}; 一起使用,但这没有效果,因为 SWIG 不知道如何处理它avformat.i:6: Warning 453: Can't apply (AVFormatContext *OUTPUT). No typemaps are defined. 我阅读了文档并考虑了它相当全面,但不包含如何为 struct 编写类型映射的示例,仅涵盖基本的 C 和 Python 类型。您能否提供结构的类型映射定义示例?将更新我的问题。
  • @vericule %apply 不是类型映射。就像#define。你需要一个%typemap
  • 谢谢,我在 %include typemaps.i 之后使用了 %apply,希望 SWIG 具有结构的通用类型映射定义。我错了。所以基本上,我需要编写自己的类型图。这是很多工作,因为 ffmpeg 结构非常复杂,这样的结构可能包含嵌套结构并且类型映射是特定于语言的。我对此并不满意,但如果这是唯一的方法,我想我别无选择。
猜你喜欢
  • 2011-12-10
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
相关资源
最近更新 更多