可以使用__getattr__ 和自定义%MethodCode;但是,有几点需要考虑:
- 需要创建一个中间类型/对象,因为
a.x 将返回一个提供__getitem__ 和__setitem__ 的对象。当发生越界时,这两种方法都应该引发IndexError,因为这是用于通过__getitem__ 进行迭代的旧协议的一部分;没有它,在迭代 a.x 时会发生崩溃。
-
为了保证向量的生命周期,a.x 对象需要维护对拥有该向量的对象 (a) 的引用。考虑以下代码:
a = A()
x = a.x
a = None # If 'x' has a reference to 'a.v' and not 'a', then it may have a
# dangling reference, as 'a' is refcounted by python, and 'a.v' is
# not refcounted.
编写%MethodCode 可能很困难,尤其是在错误情况下必须管理引用计数时。它需要了解 Python C API 和 SIP。
对于替代解决方案,请考虑:
- 设计 python 绑定以提供功能。
- 在 python 中设计类以提供使用绑定的 pythonic 接口。
虽然该方法有一些缺点,例如代码被分成更多的文件,可能需要与库一起分发,但它确实提供了一些主要好处:
- 在 python 中实现 pythonic 接口比在 C 或互操作性库的接口中容易得多。
- 对切片、迭代器等的支持可以更自然地在 python 中实现,而不必通过 C API 进行管理。
- 可以利用 python 的垃圾收集器来管理底层内存的生命周期。
- pythonic 接口与任何用于提供 python 和 C++ 之间的互操作性的实现分离。借助更扁平、更简单的绑定接口,在 Boost.Python 和 SIP 等实现之间进行更改变得更加容易。
以下是演示此方法的演练。首先,我们从基本的A 类开始。在这个例子中,我提供了一个构造函数来设置一些初始数据。
a.hpp:
#ifndef A_HPP
#define A_HPP
#include <vector>
class A
{
std::vector< double > v;
public:
A() { for ( int i = 0; i < 6; ++i ) v.push_back( i ); }
double& x( int i ) { return v[2*i]; }
double x( int i ) const { return v[2*i]; }
double& y( int i ) { return v[2*i+1]; }
double y( int i ) const { return v[2*i+1]; }
std::size_t size() const { return v.size() / 2; }
};
#endif // A_HPP
在进行绑定之前,让我们检查A 接口。虽然它在 C++ 中是一个易于使用的接口,但在 python 中却有一些困难:
- Python 不支持重载方法,当参数类型/计数相同时,支持重载的惯用语将失败。
- 对双精度(Python 中的浮点数)的引用概念在两种语言之间是不同的。在 Python 中,float 是不可变类型,所以它的值不能改变。例如,在 Python 中,语句
n = a.x[0] 绑定 n 以引用从 a.x[0] 返回的 float 对象。赋值n = 4 重新绑定n 以引用int(4) 对象;它没有将a.x[0] 设置为4。
-
__len__ 期望 int,而不是 std::size_t。
让我们创建一个有助于简化绑定的基本中间类。
pya.hpp:
#ifndef PYA_HPP
#define PYA_HPP
#include "a.hpp"
struct PyA: A
{
double get_x( int i ) { return x( i ); }
void set_x( int i, double v ) { x( i ) = v; }
double get_y( int i ) { return y( i ); }
void set_y( int i, double v ) { y( i ) = v; }
int length() { return size(); }
};
#endif // PYA_HPP
太棒了! PyA 现在提供不返回引用的成员函数,长度返回为 int。它不是最好的接口,绑定旨在提供所需的功能,而不是所需的接口。
现在,让我们编写一些简单的绑定,在 cexample 模块中创建类 A。
这是 SIP 中的绑定:
%Module cexample
class PyA /PyName=A/
{
%TypeHeaderCode
#include "pya.hpp"
%End
public:
double get_x( int );
void set_x( int, double );
double get_y( int );
void set_y( int, double );
int __len__();
%MethodCode
sipRes = sipCpp->length();
%End
};
或者,如果您更喜欢 Boost.Python:
#include "pya.hpp"
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(cexample)
{
using namespace boost::python;
class_< PyA >( "A" )
.def( "get_x", &PyA::get_x )
.def( "set_x", &PyA::set_x )
.def( "get_y", &PyA::get_y )
.def( "set_y", &PyA::set_y )
.def( "__len__", &PyA::length )
;
}
由于PyA 中间类,两个绑定都相当简单。此外,这种方法需要较少的 SIP 和 Python C API 知识,因为它需要较少的 %MethodCode 块中的代码。
最后,创建example.py,它将提供所需的pythonic接口:
class A:
class __Helper:
def __init__( self, data, getter, setter ):
self.__data = data
self.__getter = getter
self.__setter = setter
def __getitem__( self, index ):
if len( self ) <= index:
raise IndexError( "index out of range" )
return self.__getter( index )
def __setitem__( self, index, value ):
if len( self ) <= index:
raise IndexError( "index out of range" )
self.__setter( index, value )
def __len__( self ):
return len( self.__data )
def __init__( self ):
import cexample
a = cexample.A()
self.x = A.__Helper( a, a.get_x, a.set_x )
self.y = A.__Helper( a, a.get_y, a.set_y )
最后,绑定提供了我们需要的功能,而python创建了我们想要的接口。可以让绑定提供接口;但是,这可能需要深入了解两种语言之间的差异以及绑定实现。
>>> from example import A
>>> a = A()
>>> 对于 a.x 中的 x:
... 打印 x
...
0.0
2.0
4.0
>>> a.x[0] = 4
>>> 对于 a.x 中的 x:
... 打印 x
...
4.0
2.0
4.0
>>> x = a.x
>>> a = 无
>>> 打印 x[0]
4.0