首页 > 代码库 > 使用ctypes调用C共享库中函数返回值为链表式结构时的方法

使用ctypes调用C共享库中函数返回值为链表式结构时的方法

/*********************************************************************
 * Author  : Samson
 * Date    : 02/02/2015
 * Test platform:
 *              3.13.0-24-generic
 *              GNU bash, 4.3.11(1)-release 
 * *******************************************************************/

C共享库中存在这样的函数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define true 1
#define false 0

typedef struct user_server_list{
        char servername[64];
        char server_status; /* on: true off:flase*/
        char server_manual_start;  /* enable: true  disable: false*/
        struct user_server_list *next;
}Struct_server_list, *P_Struct_server_list;

int add(int a, int b)
{
        int c = a + b;
        return c;
}

P_Struct_server_list get_server_list()
{
        P_Struct_server_list p = malloc(sizeof(Struct_server_list));
        memset(p, 0, sizeof(Struct_server_list));
        strcpy(p->servername, "ssh");
        p->server_status = true;
        p->server_manual_start = false;
        P_Struct_server_list p2 = malloc(sizeof(Struct_server_list));
        memset(p2, 0, sizeof(Struct_server_list));
        strcpy(p2->servername, "cmd");
        p2->server_status = true;
        p2->server_manual_start = false;
        p->next = p2;
        p2->next = NULL;
        return p;
}
使用gcc -g -fPIC -shared -o libhelloworld.so.0.0.0 test.c编译成动态库;


然后编写python调用程序,代码如下:
#!/bin/env python  
# coding=UTF-8

from ctypes import *
class StructPointer(Structure):
        pass

StructPointer._fields_=[("servername", c_char * 64), ("server_status", c_char), ("server_manual_start", c_char), ("next", POINTER(StructPointer))]


lib = cdll.LoadLibrary(‘./libhelloworld.so.0.0.0‘)
lib.get_server_list.restype = POINTER(StructPointer)

p = lib.get_server_list()
print p.contents.servername
p2=p.contents.next[0]
print p2.servername

执行结果为:
ufo@ufo:~$ python testpython.py
ssh
cmd

使用ctypes调用C共享库中函数返回值为链表式结构时的方法