Skip to main content
 首页 » 编程设计

python之调用boost python暴露的方法函数时出现奇怪的TypeError

2025年05月04日10unruledboy

我为 box2d 编写了一个 python 包装器,一切正常,但在调用 boost python 公开的方法函数时有时会出现奇怪的 TypeError 错误。这是一种随机行为,并非每次都发生。

问题python代码:

try: 
    world = body.GetWorld()  # world is b2World instance, body is b2Body instance 
    world.DestroyBody(body)  # raise TypeError: 'NoneType' object is not callable 
except TypeError:  # catch it, and print some infomation 
    print "xxxxx", world  # I got a b2World instance here 
    print "xxxxx", sys.getrefcount(world)  # I got a value of 66 here 
    print "xxxxx", world.DestroyBody  # I got a bound method object here 
    raise 

看起来一切正常。这是怎么发生的?

还有我的包装代码的一部分:

// [file]: https://github.com/layzerar/box2d-py/blob/master/python/world.cpp 
// [project]: https://github.com/layzerar/box2d-py 
template<class T> 
inline void b2Func_ClearUserData(T& self) 
{ 
    using namespace boost::python; 
 
    xdecref((PyObject*)self.GetUserData()); 
    self.SetUserData(NULL); 
} 
inline void b2World_DestroyBody(b2World& self, b2Body* body) 
{ 
    b2Assert(self.GetBodyCount() > 0); 
    b2Assert(self.IsLocked() == false); 
 
    b2Func_ClearUserData(*body); 
    self.DestroyBody(body); 
} 
class_<b2World, b2World_W , boost::noncopyable>("b2World") 
    //... 
    .def("CreateBody", b2World_CreateBody, return_internal_reference<>()) 
    .def("DestroyBody", b2World_DestroyBody) 
    //... 
; 

我犯了明显的错误吗?

请您参考如下方法:

经过几天探索,我找到了答案。

问题我搞错了,异常真的不是DestroyBody抛出的。它由一个用 python 重写并在 DestroyBody 函数中调用的虚函数抛出。