c++ - 调用 weakref 传递的 Python 函数

标签 c++ python boost

使用 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 的情况下传递函数对象,则一切正常。有什么方法可以使它起作用吗?

最佳答案

来自 weakref documentation :

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/

相关文章:

c++ - 在 c++/MFC 中读取 key 并从 .ini 文件中获取部分

python - Panda 的双括号索引 [[]]

python - 反向传播 - 梯度误差 [Python]

c++ - 表达 >>= 运算符

c++ - 如何使用 C++ boost::asio 顺序执行异步操作?

c++ - 模板 C++ 中的实现映射出错

c++ - VC++ 中的 Windows 7 按钮样式

c++ - 如何计算ANSI C代码性能?

python - 使用 Bottlepy 初始化 - CSS 未加载

c++ - Boost 的数据驱动测试的连接运算符 `+` 损坏了第一列