python - 带有类型推导的 swig python 模板函数

标签 python c++ swig

我想将以下 C++ 代码包装到 python 模块中。

class minimal
{
public:
    minimal()
    {
    }
    ~minimal()
    {
    }

    template<class T>
    void foo(T a)
    {
        auto z = a; 
    }
};

如您所见,我有模板函数,我知道我不能在 Python 中调用模板函数,但是我希望使用 int 或 string 参数调用 foo 会成功,因为类型推导。 .cxx 文件中仍然没有 foo,但是 SWIG 文档说,它支持类型推导

所以我的目标是像这样使用 python 代码:

#C++ analog: minimal.foo(123)
minimal().foo(123) 

#C++: to minimal().foo(0.1)
minimal().foo(0.1) 

这可能吗?还是我的想法完全错误?

最佳答案

使用 %template 指令指示 SWIG 创建特定模板的实现。只有声明的模板实例可用。

例子:

%module test

%inline %{

class minimal
{
public:
    minimal()
    {
    }
    ~minimal()
    {
    }

    template<class T>
    void foo(T a)
    {
        auto z = a; 
    }
};

%}

%template(foo) minimal::foo<int>;
%template(foo) minimal::foo<double>;

例子:

>>> import test
>>> m=test.minimal()
>>> m.foo(1)
>>> m.foo(1.5)
>>> m.foo('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\test.py", line 115, in foo
    return _test.minimal_foo(self, *args)
NotImplementedError: Wrong number or type of arguments for overloaded function 'minimal_foo'.
  Possible C/C++ prototypes are:
    minimal::foo< int >(int)
    minimal::foo< double >(double)

关于python - 带有类型推导的 swig python 模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54790945/

相关文章:

python - 索引操作 (.loc) ([ ]) 和 (.) 有什么区别

python - 按索引创建嵌套列表的最小值列表

python - 如何叠加两个具有不同 WCS/分辨率的 .fits 图像?

c++ - SWIG、Python 和 Visual Studio 2012 的内存泄漏

python - 在这个Python类中,如何将值赋给 "other"变量?

c++ - 动态捕获 CPU 和内存使用情况

c++ - 来自 boost/serialization/vector #include 的链接器错误

c++ - 带有模板类的 SWIG SHARED_PTR 宏

python - SWIG:从 Python 调用 Go

c++ - Qt Widget 在初始化时被调整了两次?