假設有一個類,它實現了一個SomeType
的數組。它用C++編寫,並使用boost :: python封裝到Python中。如何包裝函數重載的類型?
BOOST_PYTHON_MODULE(my_array_module)
{
class_<MyArray>("MyArray")
// a few '.def's ...
.def("__getitem__", ???)
;
}
在Python的__getitem__
函數可以採取一個索引並返回SomeType
值,或採取一個切片對象,並返回切片。
There是如何處理在C++中重載的函數以將它們包裝到不同的Python函數中。 There是如何在Python中創建一個重載函數,如果重載意味着不同數目的參數。
但如何包裝重載功能,如果他們不同的arument類型?我需要在C++中使用2 getitem
函數。
const SomeType& getitem(PyObject *self, size_t pos) {
// ...
}
MyArray getitem(PyObject *self, slice sl) {
// ...
}
如果您嘗試使用描述hereBOOST_PYTHON_FUNCTION_OVERLOADS
方式來包裝它,它不會編譯。
我可以做一個函數
PyObject* getitem(PyObject *self, PyObject *pos_or_slice) {
extract<size_t> get_pos(pos_or_slice);
if (get_pos.check()) {
// return a single item (SomeType)
}
else {
// return a slice (MyArray)
}
}
,但我不知道如何正確地包裝成 PyObject*
,這樣,這將是與class_
產生的包裝一致。
只是直接傳遞函數,[這裏是使用boost :: python](https://gist.github.com/zed/)使用不同的C++函數(使用不同參數類型)實現的相同Python函數的示例353005#文件升壓蟒蛇-XOR-CPP-L99) – jfs 2014-10-06 02:39:39