/*********************************************************************
* 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 http://www.linuxidc.com/Linux/2013-01/78071.htm
C語言變長數組之剖析 http://www.linuxidc.com/Linux/2013-07/86997.htm
C語言需要注意的問題 http://www.linuxidc.com/Linux/2013-05/84301.htm
C語言位域的使用及其注意點 http://www.linuxidc.com/Linux/2013-07/87027.htm
C語言中簡單的for循環和浮點型變量 http://www.linuxidc.com/Linux/2013-08/88514.htm