结构中的Ctypes结构数组。如何访问0以外的索引?

时间:2017-07-23 15:50:11

标签: python c struct ctypes

我完全可以访问第一个索引。但是,其他索引不给我任何东西。他们是空白的。

这是我的c代码。

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH_UUID (256)
#define MAX_DEVICES_PER_NODE (16)

typedef struct uuid_s{
    char uuid[MAX_LENGTH_UUID];
}uuid_t;

typedef struct device_list_s{
    unsigned num_devices;
    uuid_t dev_list[MAX_DEVICES_PER_NODE];
}device_list_t;

int is04_get_device_lists(device_list_t *devl)
{
    devl->num_devices = 2;
    strcpy(devl->dev_list[0].uuid, "HEHEHEHEHE");
    strcpy(devl->dev_list[1].uuid, "NONONONONO");
    return 4;
}

int is04_pass_device_lists(device_list_t *dev_list)
{
    printf("Num Devices: %d\n", dev_list->num_devices);
    int i = 0;
    for ( ; i < dev_list->num_devices; i++)
    {
        printf("Device %d: %s\n", i, dev_list->dev_list[i].uuid);
    }
}

这是我的python代码。

from ctypes import *

MAX_LENGTH_UUID = 256
MAX_DEVICES_PER_NODE = 16

class uuid_t(Structure):
    pass
uuid_t._fields_ = [("uuid", c_char*MAX_LENGTH_UUID)]

class device_list_t(Structure):
    pass
device_list_t._fields_ = [("num_devices", c_uint),
                          ("dev_list", uuid_t*MAX_DEVICES_PER_NODE)]

def main():
    folder = os.path.dirname(os.path.abspath(__file__))
    dll_path = os.path.join(folder, "libnmos.so")
    dll = cdll.LoadLibrary(dll_path)
    print ''
    dev_list = device_list_t()
    print '[GetDeviceList] Returned value: ' + str(dll.is04_get_device_lists(byref(dev_list)))
    print '[GetDeviceList] Total devices: ' + str(dev_list.num_devices)
    print '[GetDeviceList] First Device: ' + dev_list.dev_list[0].uuid
    # print dev_list
    print '[GetDeviceList] Second Device: ' + dev_list.dev_list[1].uuid

    dev_list_2 = device_list_t()
    dev_list_2.num_devices = 2
    dev_list_2.dev_list[0].uuid = "Hello"
    dev_list_2.dev_list[1].uuid = "World"
    dll.is04_pass_device_lists(byref(dev_list_2))

    print '[PassDeviceList] dev_0: ', dev_list_2.dev_list[0].uuid
    print '[PassDeviceList] dev_1: ', dev_list_2.dev_list[1].uuid

if __name__ == '__main__':
    main()

这是输出。

[GetDeviceList] Returned value: 4
[GetDeviceList] Total devices: 2
[GetDeviceList] First Device: HEHEHEHEHE
[GetDeviceList] Second Device: 
Num Devices: 2
Device 0: Hello
Device 1: 
[PassDeviceList] dev_0:  Hello
[PassDeviceList] dev_1:  World

我无法在c和python中访问索引1。

编辑:添加了c include。

系统信息: Linux bthapa-dev 4.4.0-83-generic#106-Ubuntu SMP Mon Jun 26 17:54:43 UTC 2017 x86_64 x86_64 x86_64 GNU / Linux

bthapa @ bthapa-dev:/ usr / bin $ python 的/ usr /斌/蟒

bthapa @ bthapa-dev:/ usr / bin $ ls -al python lrwxrwxrwx 1 root root 9月30日22:51 python - &gt; python2.7

0 个答案:

没有答案