使用 Boost.Python,有没有办法调用通过 weakref
传递的 Python 函数?以下代码不起作用:
import weakref
def foo():
print 'it works'
def func():
return weakref.ref(foo)
下面是C++:
object module = import("test");
object func(module.attr("func"));
object foo = func();
foo(); // Should print 'it works', but it prints nothing
但是,如果我在不使用 weakref 的情况下传递函数对象,则一切正常。有什么方法可以使它起作用吗?
最佳答案
Return a weak reference to object. The original object can be retrieved by calling the reference object if the referent is still alive...
因此,根据您的代码段:
import weakref
def foo():
print "It Works!"
def func():
return weakref.ref(foo)
ref = func() # func returns the reference to the foo() function
original_func = ref() # calling the reference returns the referenced object
original_func() # prints "It Works!"
关于c++ - 调用 weakref 传递的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919134/