2012-10-12 83 views
1

我需要編寫一個具有將由C函數調用的回調的python調用。 C頭文件具有以下從結構字段Python的CTypes回調

... 
typedef struct _myResponse { 
    char * data, 
    void (*setResponseFunc)(const char * const req, char ** dataptr); 
} MyResponse_t 

C庫調用像在C這個

void process(const char * const req , MyResponse_t *response) { 
    response->SetResponseFunc("some request", &response->data); 
} 

樣品回調實現回調的回調:

void SetResponse(const char *respData, char **dataptr) { 
     char *ptr = malloc(strlen(respData)); 
     strcpy(ptr, respData); 
     *dataptr= ptr; 
} 

然後我用ctypesgen來生成python代碼。生成的文件包含以下內容:

agent.py:

def String: 
... 

class struct__myResponse(Structure): 
    pass 

struct__myResponse.__slots__ = [ 
    'data', 
    'SetResponseFunc', 
] 
struct__myResponse._fields_ = [ 
    ('data', String), 
    ('SetResponseFunc', CFUNCTYPE(UNCHECKED(None), String, POINTER(String))), 
] 

這就是我試圖用它

CALLBACK_FUNC = CFUNCTYPE(c_agent.UNCHECKED(None), agent.String, POINTER(agent.String)) 

def PyCopyResponse(a,b): 
    print "XXXXXX" // here, I haven't tried to implement the proper code, just want to see if the callback is called from the C library 

copy_response = CALLBACK_FUNC(PyCopyResponse) 

調用它

agentResp = agent.MyResponse_t(None,copy_response) 

    agent.process("some value",agentResp) 

我不看」我的python回調實現被調用。我已經驗證C庫正在適當地調用回調函數。任何人都可以幫忙嗎?

回答

0

好的,找到了問題。該過程需要一個指向結構的指針,我直接傳遞結構。

data = agent.String() 
agentResp = agent.MyResponse_t(data,copy_response) 
agentResp_p = pointer(agentResp) 

agent.process("some value",agentResp_p)