最近看了下用Boost.Python封裝C++供Python調用。在搗鼓的過程中遇到一個費解的異常:
TypeError: unbound method Boost.Python.function object must be called with MyClass instance as first argument (got nothing instead)
最終盡管可以正常使用了,但仍是一頭霧水。
前期工作
1. 用Python封裝C++類Vector3:
1
class_<Vector3>("Vector3")
2
.def_readwrite("x", &Vector3::x)
3
.def_readwrite("y", &Vector3::y)
4
.def_readwrite("z", &Vector3::z)
5
.def("normalise", &Vector3::normalise)
6
.def("length", &Vector3::length)
7
.def("distance", &Vector3::distance)
8
.def(self += self)
9
.def(self -= self)

2

3

4

5

6

7

8

9

2. 用Python調用
構造一個Vector3對象,測試其功能



3. 輸出結果






4. 修改測試腳本:



運行正常。
問題分析
Python拋出的異常說是unbound method的問題,實在找不出封裝的過程有什么問題。
仔細分析下可以猜測2中的pt似乎并不是Vector3的一個實例。
驗證一下:









輸出結果:
<AnyCADPlatformPython.Vector3 object at 0x04732FC0>
<class 'AnyCADPlatformPython.Vector3'>
至此真相大白。