2011-08-02 3 views
0

Boost.Python을 사용하면 weakref을 통해 전달 된 파이썬 함수를 호출 할 수있는 방법이 있습니까? 다음 코드는 작동하지 않습니다weakref에서 전달 된 파이썬 함수 호출

import weakref 

def foo(): 
    print 'it works' 

def func(): 
    return weakref.ref(foo) 

다음은 ++은 C입니다 : 내가 weakref없이 함수 객체를 전달하면

object module = import("test"); 
object func(module.attr("func")); 
object foo = func(); 
foo(); // Should print 'it works', but it prints nothing 

그러나, 모든 것이 잘 작동합니다. 이 일을 할 수있는 방법이 있습니까? weakref documentation에서

+0

이 땅 ++ C에 걸쳐 수행하지만,이'weakref.ref' 호출하면 파이썬에서 강력한 객체에 대한 참조 (또는'None')을 반환하는 경우 몰라요 ... – delnan

+0

@delnan은에 따르면 문서에 약한 참조를 반환합니다. 하지만 ref()와 proxy()의 차이를 이해하지는 못합니다. –

답변

5

:

반환 객체에 대한 약한 참조. 원래 객체가

이 그래서, 당신의 조각을 주어 ... 참조 객체 지시 대상이 아직 살아 있다면 호출하여 검색 할 수 있습니다 :

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!" 
4

이 당신을 위해 그것을 해결할 수 있습니다.

>>> import weakref 
>>> def foo(): print 'it works' 
... 
>>> x = weakref.ref(foo) 
>>> x()() 
it works 
>>> x() 
<function foo at 0x7f56c10acc80>