Python调用C/C++

一、问题

      Python提供的ctypes库,它提供同C语言兼容的数据类型,可以很方便地调用C语言动态链接库中的函数。ctypes 的官方文档可以参考:https://docs.python.org/2/library/ctypes.html

二、Python调用C/C++

1、Python调用C动态链接库的简单例子:

        Python调用C库比较简单,不经过任何封装打包成so,再使用python的ctypes调用即可。
(1)C语言文件:pycall.c

/***gcc -o libpycall.so -shared -fPIC pycall.c*/  
#include <stdio.h>  
#include <stdlib.h>  
int foo(int a, int b)  
{  
  printf("you input %d and %d\n", a, b);  
  return a+b;  
}  


(2)gcc编译生成动态库libpycall.so:gcc -o libpycall.so -shared -fPIC pycall.c。使用g++编译生成C动态库的代码中的函数或者方法时,需要使用extern "C"来进行编译。

(3)Python调用动态库的文件:pycall.py
import ctypes  
ll = ctypes.cdll.LoadLibrary   
lib = ll("./libpycall.so")    
lib.foo(1, 3)  
print '***finish***'  
(4)运行结果:


2、Python调用C/C++接口需要类型匹配的例子、

(1)、c语言头文件和源文件ctest.h、ctest.c

/******************************************ctest.h**********************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h> 
struct segment{
    int key;

struct content{
    struct segment seg;
    int value

struct content g_conent; 
int set_kv(int key,int value);
struct content *get_content();

/********************************************ctest.c***********************************/

#include "ctest.h" 
int set_kv(int key,int value)
{
    g_content.seg.key=key;
    g_content.value=value;
    return 0;

struct content *get_content()
{
    return &g_content;
}

(2)编译成动态库so文件:gcc ctest.c -fPIC -shared -o ctest.so

(3)编写python代码pycall2.py

from ctypes import *
libctest = cdll.LoadLibrary('ctest.so')
 
class segment_py(Structure):
    _fields_=[("key",c_int)]
 
class content_py(Structure):
    _fields_=[("seg",segment_py),
              ("value",c_int)]
 
libctest.get_content.restype=POINTER(content_py)
 
def test():
    con=content_py()
    libctest.set_kv(1,10)
    con=libctest.get_content()
    print "key:%s value:%s " % (con.seg.key,con.value)
 
if __name__ == '__main__'
    test()


(4)运行py:$python3 pycall2.py

运行结果略。

三、ctypes库定义的与C匹配的类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值