简体   繁体   English

如何使用SWIG在命名空间内的模板类中包装C ++ operator []?

[英]How to use SWIG to wrap a C++ operator[] in a template class inside a namespace?

I'm using SWIG to wrap an existing C++ library using just its header files. 我正在使用SWIG仅使用其头文件来包装现有的C ++库。 This library uses a namespace and a template class to create Arrays of custom objects. 此库使用命名空间和模板类来创建自定义对象的数组。 I'm running into problems trying to wrap the subscript operator (operator[]) used to access elements inside the wrapped arrays. 我在尝试包装用于访问包装数组内部元素的下标运算符(operator [])时遇到了问题。 SWIG tells me that operator[] is ignored and that I should use %extend instead: SWIG告诉我操作符[]被忽略,我应该使用%extend代替:

small.i:18: Warning 389: operator[] ignored (consider using %extend)

So I'm trying to use extend but no matter what syntax I've tried, I can't get the inserted code to show up in the _wrap.cxx file. 所以我试图使用extend但是无论我尝试了什么语法,我都无法将插入的代码显示在_wrap.cxx文件中。 Here's my SWIG input file: 这是我的SWIG输入文件:

%module tltest
%{
...
%}

namespace nite {
    template <class T> class Array {
    public:
        %rename(__getitem__) operator[];
        const T& operator[](int index) const {return m_data[index];}

        %rename(__len__) getSize;
        int getSize() const {return m_size;}
    };

    class UserData : private NiteUserData
    {
    public:
    };

    %template(userDataArray) Array<UserData>;

};

%extend Array<UserData> {
    UserData& __getitem__(unsigned int i) {
        return $self[i];
     }
}

I know that I want to define the __getitem__ function for Python to be able to index into the array class. 我知道我想为Python定义__getitem__函数以便能够索引到数组类。 Note that the __len__ function does get renamed correctly, and works properly from the Python interface. 请注意, __len__函数确实已正确重命名,并且可以从Python界面正常工作。

However, that %extend block that I added to define the __getitem__ call does not ever seem to get injected into the small_wrap.cxx wrapper file. 但是,我添加的用于定义__getitem__调用的%扩展块似乎永远不会被注入到small_wrap.cxx包装文件中。 Can anyone see what I'm doing wrong? 谁能看到我做错了什么?

Aha! 啊哈! I discovered that you need to qualify all types using the namespace in the %extend block, as follows: 我发现您需要使用%extend块中的命名空间限定所有类型,如下所示:

%extend nite::Array<nite::UserData> {
    nite::UserData __getitem__(unsigned int i) {
        return (*($self))[i];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM