来自结构字段的Python CTypes回调

2024-10-04 05:20:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个python调用,它有一个由C函数调用的回调函数。C头文件包含以下内容

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

C库像这样调用回调

^{pr2}$

C中回调的示例回调实现:

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

然后使用ctypesgen生成python代码。生成的文件包含以下内容:

在代理.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库是否正确地调用了回调。谁能帮忙吗?在


Tags: thenonedatastringdefstructagentchar
1条回答
网友
1楼 · 发布于 2024-10-04 05:20:52

好的,找到问题了。这个过程需要一个指向一个结构的指针,我直接传递这个结构。在

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

agent.process("some value",agentResp_p)

相关问题 更多 >