I need to write a python call that has a callback that will be invoked by C function. The C header file has the following
...
typedef struct _myResponse {
char * data,
void (*setResponseFunc)(const char * const req, char ** dataptr);
} MyResponse_t
The C library calls the callback like this
void process(const char * const req , MyResponse_t *response) {
response->SetResponseFunc("some request", &response->data);
}
Sample callback implementation of the callback in C:
void SetResponse(const char *respData, char **dataptr) {
char *ptr = malloc(strlen(respData));
strcpy(ptr, respData);
*dataptr= ptr;
}
I then use ctypesgen to generate the python code. The generated file contains the following:
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))),
]
this is how I tried to use it
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)
Calling it
agentResp = agent.MyResponse_t(None,copy_response)
agent.process("some value",agentResp)
I dont’ see my python callback implementation to be called at all. I have verified that the C library is calling the callback appropriately. Can anyone please help?
Ok, found the issue. The process takes a pointer to a structure, I was passing the structure directly.