2012-05-22 4 views
2

I는 C의 코드를 가지고콜백 함수

typedef result function_callback(struct mes_t* message, void* data) 
struct mes_t 
{ 
uint32_t field1 
uint32_t field2 
void* data 
}; 
function_one(&function_callback, data) 

응용 프로그램이 호출하는 사용자 정의 콜백 함수 function_callback합니다 ( function_one에서). field1, field2 및 데이터 매개 변수 (데이터는 일반적으로 0과 같습니다)에 전달 된 콜백 함수에서이 예제의 파이썬 코드가 올바르게 작성되었는지 여부를 나타냅니다.

class mes_t(ctypes.Structure): 
    pass 
mes_t._fields_ = [ 
    ('field1', ctypes.c_uint32), 
    ('dfield2', ctypes.c_uint32), 
    ('data', ctypes.POINTER(ctypes.c_void_p))] 
data_t=ctypes.c_void_p 
data=data_t() 
CALLBACK=CFUNCTYPE(ccg_msg, data_t) 
cb_func=CALLBACK() 
result = function_one(ctypes.byref(cb_func), ctypes.byref(data)) 
+0

샘플 코드를 수정하는 데 도움이 될 수 있습니다. C 선언문은 유효하지 않습니다 (여러분은 세미콜론이 누락되어 잘못된 순서로 물건을 놓고있는 것 같습니다) 그리고'ccg_msg'가 무엇인지는 명확하지 않습니다. –

답변

1

여기 코드를 해석하는 올바른 방법을 추측했습니다. 여기 조정 된 샘플 조각 :

typedef int /* or whatever */ result; 

struct mes_t 
{ 
    uint32_t field1; 
    uint32_t field2; 
    void* data; 
}; 
typedef result function_callback(struct mes_t* message, void* data); 
result function_one(function_callback fcb, void* data); 

그리고 여기에 몇 가지 예 function_one()의 사용을 만들기위한 파이썬을하는 ctypes의 :

class mes_t(ctypes.Structure): 
    _fields_ = (
     ('field1', ctypes.c_uint32), 
     ('field2', ctypes.c_uint32), 
     ('data', ctypes.c_void_p)) 

result_t = ctypes.c_int; # or whatever 

callback_type = ctypes.CFUNCTYPE(result_t, ctypes.POINTER(mes_t), ctypes.c_void_p) 
function_one.argtypes = (callback_type, ctypes.c_void_p) 
function_one.restype = result_t 

data_p = ctypes.c_char_p('whatever') 

def the_callback(mes_p, data_p): 
    my_mes = mes_p[0] 
    my_data_p = ctypes.cast(data_p, ctypes.c_char_p) # or whatever 
    my_data = my_data_p.value 
    print "I got a mes_t object! mes.field1=%r, mes.field2=%r, mes.data=%r, data=%r" \ 
      % (my_mes.field1, my_mes.field2, my_mes.data, my_data) 
    return my_mes.field1 

result = function_one(callback_type(the_callback), ctypes.cast(data_p, ctypes.c_void_p)) 
당신이 당신의 코드 사이에 많은 차이가 나타납니다

; 아마도 모든 것에 대한 완전한 설명을하기에는 너무 많은 것입니다. 그러나 특히 혼란스럽게 보이는 부분이 있으면 몇 가지 특정 부분을 설명 할 수 있습니다. 그러나 일반적으로 ctypes 포인터가 어떻게 작동하는지 잘 이해하는 것이 중요합니다. 예를 들어, 포인터를 void로 포인터하지 않으려 고합니다.하지만 파이썬 코드가 그랬습니다.

+0

다음은 작동 예제입니다. https://gist.github.com/Nican/5198719 – Nican