python - Swiging 作为模板函数的类成员函数

标签 python c++ swig

此问题基于以下问题: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)

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

可以通过在接口(interface)文件中重载、扩展等方式获得更简洁的接口(interface),例如

%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 获取上面的接口(interface)(通过扩展),无需扩展

最佳答案

幸运的是,Python 包装器支持重载,因此您可以简单地用相同的名称实例化这两个方法,SWIG 会在运行时施展魔法来解决重载问题。参见 6.18 Templates在文档的“SWIG 和 C++”一章中了解更多详细信息。

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

关于python - Swiging 作为模板函数的类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51254957/

相关文章:

c++ - build 世界时钟

swig - 在 SWIG 接口(interface)中忽略 __attribute__((packed)) 是否总是安全的?

c - 中止(核心转储)与 *** 错误在 `python3.6' : corrupted size vs. prev_size:0x0000000000e018e0 ***

c - 痛饮错误 : Syntax Error in input(1)

c++ - Cocos2d-x 3.0 不同 anchor 的旋转序列

c++ - 函数返回非引用变量和引用变量之间的差异

python - 这段 Fortran 77 代码的意图是什么?

python - 由不同的 train_test_ratio 引起的 Shogun/二次 MMD 误差

Python 诗歌在 Ubuntu 上失败

python - 对一些杂乱的数据进行迭代和平均