【问题标题】:swig python template functions with type deduction带有类型推导的 swig python 模板函数
【发布时间】:2019-02-20 16:21:27
【问题描述】:

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

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

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

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

所以我的目标是像这样编写 python 代码:

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

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

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

【问题讨论】:

    标签: python c++ swig


    【解决方案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)
    

    【讨论】:

    • 感谢您的回答,但如果我们明确告诉 SWIG 如何包装函数,自动类型推断似乎不起作用。它让我想起了 C++ 中的显式实例化
    • @Demaunt 在 C++ 中,编译器查看模板的所有用途并为它们生成代码。在 Python 中,扩展已经被编译,所以%template 指示 SWIG 为您要提前支持的类型生成代码。
    猜你喜欢
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2010-12-27
    相关资源
    最近更新 更多