使用ctypes的回调函数 [英] Callback functions using ctypes
问题描述
我在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_one )回调函数 function_callback 。
在传递的回调函数中使用field1,field2和data参数(数据通常等于0)
The application calls the user-defined (in the function_one) callback function function_callback. In the callback function passed field1, field2 and data parameters (data is usually equal to 0)
此示例中python上的代码是否正确编写?
Whether the code on a python for this example is correctly written?
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))
推荐答案
我猜这里解释代码的正确方法。调整后的示例代码段如下:
I've guessed here the right way to interpret your code. Adjusted sample snippets here:
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 Python示例。 code>:
And here's some example ctypes Python for making use of function_one()
:
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的指针,但这就是您的python代码所做的事情。)
You'll see there are numerous differences between this and your code; probably too much to give full explanations of everything. I can, however, explain a few particular parts if there are some which seem especially confusing. In general, though, it's important to have a good understanding of how ctypes pointers work (for example, you probably don't want a pointer to a pointer to void, but that's what your python code did).
这篇关于使用ctypes的回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!