k668 发表于 2017-4-25 12:24:15

python-调用C动态库

哥虽然作为屌丝程序员,但是也算是一个优雅的程序员,平时常用都是python、java、shell、as这些高贵无比的语言,像C、C++那样的屌丝语言,是有多远跑多远。

首先,不是C语言不好,只是指针操作,字符串操作,实在是恶心得要命,能弄懂c那一套编程方法,那绝对是屌丝中的屌丝。

哥,今天也不得不屌丝了一把,搞了一下C。

首先哥从事的的是测试工作,测试框架是python写的,但是开发同学提供的接口是C的,python和C怎么结合在一起。百度一下,很简单就是用python调用C的动态链接库即可完成。那么具体是怎么实现呢?

首先第一个程序 hello_world 呵呵~~~~~~~~

1. C源程序:
//hello.c
#include<stdio.h>

void hello(char *name)
{
   printf ("Hello %s \n",name);
   return;
}

2.编译成C动态链接库 gcc -fPIC -shared hello.c -o libhello.so
目录下多了一个libhello.so 有木有

3. 编写python 程序
#py_hello.py
from ctypes import *
lib_handler = CDLL("libhello.so")

lib_handler.hello("wuyn") # 输出 hello wuyn 有木有啊

---------------------------------------------------------------------------------------------
你以为这事就这么完了吗。。。呵呵。。。。。

当我一看同事提供接口的时候。。。呵呵。。。。。你以为就这么简单hello_world 吗

好吧。。。再改。。。。。一般工作中用到的数据类型不仅仅是基本数据类型那么简单。。。一般是结构体多层嵌套。。。。说实话(不搞多几层指针已经说明他是爱你的了。。。)

下面介绍简单的结构体及指针相关的使用。。。。

1. //C源程序头文件

//person.h
#include <string>
#include <stdio.h>
#include <malloc.h>

#ifndefPERSON_H
#define PERSON__H

typedef struct PERSON
{
   char name;
   int    age;
   int    sex
};

PERSON* init(char* name, int age, int sex);
char* getName(PERSON *p);
int getAge(PERSON *p);
int getSex(PERSON *p);
#endif

2.//C源程序
#include "person.h"

PERSON* init(char* name, int age, int sex)
{
      PERSON *person = (PERSON*)malloc(sizeof(PERSON));
      strcpy(person->name,name);
      person->age = age;
      person->sex = sex;
      return person;
}

char* getName(PERSON *p)
{
       if(p)
      {
             return p->name;
      }
}

int getAge(PERSON *p)
{
      if(p)
      {
            return p->age;
      }
}

int getSex(PERSON *p)
{
      if(p)
      {
            return p->sex;
      }
}

3. 把C程序编译成动态链接库
gcc -fPIC -shared person.c -o libperson.so

4. 编写python 程序

#py_person.py

from ctypes import *

#声明一个类继承Structure 其实是和C源代码中的struct结构相对应(如果你问,你是怎么知道的?。。。额。。看看python2.7 帮助文档。。。。)
class Person(Structure):

      _fields_ = [("name",c_char_p),("age",c_int),("sex",c_int)]

lib_handler = CDLL("libperson.so")

init = lib_handler.init

init.restype=POINTER(Person) #声明init方法的返回值类型

p = init("wuyn",23,1)

getName = lib_handler.getName

getName.restype=c_char_p #声明getName方法返回值类型

print getName(p)

getAge = lib_handler.getAge

getAge.restype = c_int #声明getAge方法返回值类型

print getAge(p)

getSex = lib_handler.getSex

getSex.restype = c_int #声明getSex方法返回值类型

print getSex(p)


其实这些零碎的片段都在python帮助文档里面有详细介绍,大伙还不知道怎么用不着急,可以在需要时候打开帮助文档,按里面的例子照写错不了。。。第一次调不出来没关系。。继续研究。。O(∩_∩)O哈哈~~~~~~~
页: [1]
查看完整版本: python-调用C动态库