给定这组文件:
foo.h:
#pragma once
#include <stdio.h>
template <class T0> class Foo {
public:
T0 m[3];
Foo(const T0 &a, const T0 &b, const T0 &c) {
m[0] = a;
m[1] = b;
m[2] = c;
}
void info() { printf("%d %d %d\n", m[0], m[1], m[2]); }
// T0 &operator[](int id) { return ((T0 *)m)[id]; }
};
foo.cpp:
#include "foo.h"
foo.i(尝试1):
%module foo
%{
#include "foo.h"
%}
%include "foo.h"
%template(intFoo) Foo<int>;
%extend Foo{
T0& __getitem__(int id) { return ((T0 *)m)[id]; }
}
setup.py:
import os
import sys
from setuptools import setup, Extension
foo_module = Extension('_foo',
sources=[
'foo.i',
'foo.cpp'
],
swig_opts=['-c++', '-py3', '-builtin'],
include_dirs=['.']
)
setup(name='foo',
version='0.1',
platforms=['Windows', 'Linux'],
ext_modules=[foo_module],
py_modules=["foo"],
)
test.py:
from foo import intFoo
a = intFoo(10,20,30)
print(dir(a))
a.info()
print(a[2])
我构建了运行的扩展程序:
python setup.py build_ext --force -i
但是当我尝试运行 test.py 文件时,会出现以下错误:
TypeError: 'foo.intFoo' object does not support indexing
foo.i
中的extend
语句是其他SO相关线程上建议的答案,这意味着我在这里使用它不正确。有人能解释一下如何修复此问题,以便当我运行test.py
时可以成功使用[]
运算符吗?
其他尝试:
Attempt2:
%module foo %{ #include "foo.h" %} %include "foo.h" %template(intFoo) Foo<int>; %extend intFoo{ T0& __getitem__(int id) { return ((T0 *)m)[id]; } }
Throws this error
TypeError: 'foo.intFoo' object does not support indexing
Attempt3
%module foo %{ #include "foo.h" %} %include "foo.h" %extend Foo{ T0& __getitem__(int id) { return ((T0 *)m)[id]; } } %template(intFoo) Foo<int>;
Throws this error
foo_wrap.cpp(3808): error C2065: 'm': undeclared identifier
%extend intFoo
或将%extend Foo
移至%template(intFoo)
之前。 - Mark Tolonen