使用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

执行结果为

linuxidc@linuxidc:~$ python testpython.py
ssh
cmd

C++ 隐式类类型转化 Implicit Class-Type Conversions

C语言变长数组之剖析

C语言需要注意的问题

C语言位域的使用及其注意点

C语言中简单的for循环和浮点型变量

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0681500e37e063a72e5a4ed6324c5e56.html