Python c函数的ctypes内存分配

Python Ctypes memory allocation for c function

我目前有一个 python 回调函数,它使用 ctypes 库调用 c 函数。 c 函数需要一个指向结构的指针,例如 animal_info_s。我实例化结构并将其作为指向 c 函数的指针传递,并且它可以工作。我遇到的问题是当我有多个线程调用回调时,我发现传回的信息在线程之间混淆了。

class animal_info_s(ctypes.Structure):
    _fields_ = [('dog_type',          ctypes.c_uint16),
                ('cat_type',          ctypes.c_uint16),
                ('bird_type',         ctypes.c_uint16),
                ('epoch_time',        ctypes.c_uint16),
                ('more_information',  ctypes.c_uint16)]


_mod = ctypes.cdll.LoadLibrary('bbuintflib.dll')
animal_info_s = animal_info_s()
get_animal_data = _mod.get_animal_data
get_animal_data.argtypes = [ctypes.POINTER(animal_info_s)]
get_animal_data.restype =   ctypes.c_int

# Python Callback
def GetAnimalData():
    animal_info_p = animal_info_s
    res = get_animal_data(animal_info_p)
    if (res != 0):
        print("Failed to get animal info")
        return

    print ("Receive Time - %d\nDog: %d\nCat: %d\nBird:%d" %(animal_info_p.epoch_time,
                                                            animal_info_p.dog_type,
                                                            animal_info_p.cat_type,
                                                            animal_info_p.bird_type))

我认为发生的事情是当我实例化结构时,它每次都使用相同的内存位置。如何为调用回调的每个线程创建新的内存位置?

应删除以下行。它将名称 animal_info_s 重新定义为 class animal_info_s 实例,然后隐藏 class.

animal_info_s = animal_info_s()

以下行应更改为:

animal_info_p = animal_info_s

至:

animal_info_p = animal_info_s()

原始行为第一个错误的 animal_info_s 名称取了另一个名字,这是线程中使用的唯一实例。每次调用回调时,推荐行都会创建 animal_info_s class 的新实例。