【问题标题】:Swigging a class member function that is a template function挥动作为模板函数的类成员函数
【发布时间】:2018-07-09 22:39:34
【问题描述】:

此问题基于以下问题:How to instantiate a template method of a template class with swig?

但是,与那个问题相比,我试图包装的代码有点不同:

class MyClass {
  public:
    template <class T>
     void f1(const string& firstArg, const T& value);
};

MyClass 是一个普通的 C++ 类,有一个模板函数 f1。

尝试包装 MyClass::f1:,即 Swig .i 文件

 %template(f1String)    MyClass::f1<std::string>; 

有了上面的,一个Python客户端就可以做到了

o = MyClass
str1 = "A String"
o.f1String("", str1)

此接口要求 Python 客户端了解所有不同的 f1 函数名称,每个函数名称因类型而异。不太干净。

可以通过重载、扩展接口文件来获得更干净的接口,例如

%extend MyClass {
   void f1(const string& s, const string& s1){
          $self->f1(s, s1);
   }
   void f1(const string& s, const int& anInt){
          $self->f1(s, anInt);
   }
}

这允许这样的客户端代码:

o = MyClass
str1 = "A String"
anInt = 34
o.f1("", str1)
o.f1("", anInt)

问题是,有没有办法使用Swig(通过扩展)获得上述接口,无需扩展

【问题讨论】:

  • 你能显示实际输出而不是“我收到类型错误”吗?
  • 另外,如果你怀疑非模板参数是问题所在,你为什么不测试一下呢?暂时添加template &lt;class T&gt; void f2(const T&amp; value);%template(f2String) MyClass::f2&lt;std::string&gt;; 看看是否可行。如果没有,您可以排除,而不仅仅是猜测。
  • 等一下,你问的错误是怎么回事?这似乎是一个与一分钟前完全不同的问题。
  • 我最初的问题在 T 参数中存在问题,不是参考。我删除了它,所以代码编译得很好。问题是关于如何获得更干净的界面。抱歉给您带来了困惑,阿巴纳特!

标签: python c++ swig


【解决方案1】:

幸运的是,Python 包装器支持重载,因此您可以简单地实例化两个具有相同名称的方法,SWIG 将在运行时发挥它的魔力来解决重载。有关详细信息,请参阅文档的“SWIG 和 C++”一章中的6.18 Templates

test.i

%module example
%{
#include<iostream>

class MyClass {
public:
    template <class T>
    void f1(const std::string& firstArg, const T& value) {
        std::cout << firstArg << ',' << value << '\n';
    }
};
%}

%include <std_string.i>

class MyClass {
public:
    template <class T>
    void f1(const std::string& firstArg, const T& value);
};

%extend MyClass {
    %template(f1) f1<std::string>;
    %template(f1) f1<int>;
}

test.py

from example import *

o = MyClass()
str1 = "A String"
anInt = 34
o.f1("X", str1)
o.f1("Y", anInt)

编译和运行的示例工作流程:

$ swig -python -c++ test.i
$ g++ -Wall -Wextra -Wpedantic -I /usr/include/python2.7/ -fPIC -shared test_wrap.cxx -o _example.so -lpython2.7
$ python2.7 test.py
X,A String
Y,34

【讨论】:

  • 确实很优雅!
猜你喜欢
  • 2023-04-02
  • 2016-06-25
  • 2011-07-06
  • 2013-07-02
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
相关资源
最近更新 更多