我如何编写函数以在SWIG中接受小数对象?

问题描述 投票:0回答:1

我正在使用SWIG在Python和我们的C ++视频处理库之间编写接口。在python中,我使用Fraction类表示帧频(例如NTFS24 = 24000/1001 FPS)。所讨论的功能是视频转码,即获取视频(或帧流)输入并产生类似的输出。为此,我们需要指定输出(有时是输入)帧速率。

有什么方法可以在C ++(SWIG)端连接Fraction类?根据我在Internet上发现的信息,应该可以将tuple传递给std::pair<int,int>参数,所以这是我的后备计划,但是有更好的方法吗?谢谢!

python c++ swig fractions
1个回答
0
投票

我整理了以下接口文件,以说明如何包装分数。最后,我决定创建自己的分数结构以将分数保留在C ++端,这主要是因为它比使用std::pair<int, int>的含义要少。 (我认为一对整数也可以是2D坐标,或者是屏幕分辨率或许多其他类型,对于过载分辨率等而言,更强的键入是更好的选择。)

%module test

%{
#include <iostream> // Just for testing....

static PyObject *fractions_module = NULL;
%}

%init %{
  // Import the module we want
  fractions_module = PyImport_ImportModule("fractions");
  assert(fractions_module);
  // TODO: we should call Py_DECREF(fractions_module) when our module gets unloaded
%}

%typemap(in) const Fraction& (Fraction tmp) {
  // Input typemap for fraction: duck-type on attrs numerator, denominator
  PyObject *numerator = PyObject_GetAttrString($input, "numerator");
  PyObject *denominator = PyObject_GetAttrString($input, "denominator");

  int err = SWIG_AsVal_int(numerator, &tmp.numerator);
  assert(SWIG_IsOK(err)); // TODO: proper error handling
  err = SWIG_AsVal_int(denominator, &tmp.denominator);
  assert(SWIG_IsOK(err)); // TODO: errors...

  Py_DECREF(numerator);
  Py_DECREF(denominator);

  $1 = &tmp;  
}

%typemap(out) Fraction {
  // Output typemap: pass two ints into fractions.Fraction() ctor
  $result = PyObject_CallMethod(fractions_module, "Fraction", "ii", $1.numerator, $1.denominator);
}

%inline %{
  struct Fraction {
    int numerator, denominator;
  };

  void fraction_in(const Fraction& fraction) {
    std::cout << fraction.numerator << "/" << fraction.denominator << "\n";
  }

  Fraction fraction_out() {
    Fraction f = {100, 1};
    return f;
  }
%}

通常,这只是两个类型映射-一个用于C ++函数的输入,另一个用于输出。他们从输入对象的分子和分母属性构造一个临时的C ++分数,并分别从我们的C ++构造一个fractions.Fraction Python对象。使它们适应其他相似的分数类型应该非常简单。

© www.soinside.com 2019 - 2024. All rights reserved.