欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python ctypes 回调函数_Python ctypes中具有自定义类型的回调

发布时间:2025/3/19 python 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python ctypes 回调函数_Python ctypes中具有自定义类型的回调 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

那里有一些错误,有些是基本的Python错误:

from ctypes import *

class A(Structure):

_fields_ = [

("a1", c_char_p),

("a2", c_int)]

class Callback(object):

def outputCallback(self, a, b): # outputCallback(): ?

print a.contents.a1, a.contents.a2

# The prototype of the `outputCallback`

# tells that it returns nothing, `void`

cb = Callback()

CMPFUNC = CFUNCTYPE(None, POINTER(A), c_void_p) # so `restype` shoud be

# None, void

cb.cmp_func = CMPFUNC(cb.outputCallback)

libc = CDLL('library.so')

libc.function1(0, 0, cb.cmp_func, 0, 0)

测试DLL:

#include

#ifdef _WIN32

#define DLLEXPORT __declspec(dllexport)

#else

#define DLLEXPORT

#endif

#ifdef __cplusplus

extern "C" {

#endif

typedef struct A

{

const unsigned char* a1;

unsigned int a2;

} A;

int DLLEXPORT function1(int a,

int b,

void (*outputCallback)(const A* a, void* b),

int c,

int d)

{

A obj;

obj.a1 = "Hello";

obj.a2 = 5;

outputCallback(&obj, NULL);

return 0;

}

#ifdef __cplusplus

};

#endif

测试:

>gcc library.c -o library.so -shared

>python py.py

Hello 5

>

总结

以上是生活随笔为你收集整理的python ctypes 回调函数_Python ctypes中具有自定义类型的回调的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。