码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-02-02 21:37:30      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

/*********************************************************************
 * 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共享库中函数返回值为链表式结构时的方法

标签:

原文地址:http://blog.csdn.net/yygydjkthh/article/details/43413475

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!