c++调用dll_Python如何去调用C语言编写的动态链接库?

软硬件环境

  • ubuntu 18.04 64bit

  • windows 10 64bit

  • Python 3.5.1

  • GCC 4.9

  • visual studio

前言

最近在做python3开发中,碰到了一个问题,需要通过调用C的一个动态链接库来获取相应的值。扒了扒网络,动手实践了下,形成此文。

linux版的动态库

写个简单的C代码,test.c

1#include 2#include 34char * printStr(const char *p,const char *q)5{6    printf("%s",p);7    printf("%s",q);8    return "djstava";9}

通过以下命令编译成动态链接库

1gcc -fPIC -shared -o libtest.so test.c

python3中调用

要调用C库中的函数,需要用到ctypes这个模块

 1# -*- coding: utf-8 -*-
2__author__ = 'djstava'
3
4from ctypes import *
5
6handle = cdll.LoadLibrary('libtest.so')
7func = handle.printStr
8func.argtypes = (c_char_p,c_char_p)
9func.restype = c_char_p
10tmp = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))
11print(tmp.decode("utf-8"))

程序执行结果

1helloworlddjstava

程序解释

1func.argtypes = (c_char_p,c_char_p)
2func.restype = c_char_p

这2句是分别设置参数数据类型和返回值类型,如果不进行设置,直接调用的话,参数可以正常接收,但是返回值永远是个int值,传入的字符串参数必须为encode("utf-8"),否则在c库中仅会打印为首字符

1handle = cdll.LoadLibrary('libtest.so')
2ret = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))

关于其它数据类型的argtypes的设置,请查阅参考文献中的链接

windows版的动态库

Visual Studio编译dll,在需要抛出的方法前加入__declspec(dllexport), 比如下面C代码

 1__declspec(dllexport) unsigned int crc32( const unsigned char *s, unsigned int len) 2{
3  unsigned int i;
4  unsigned int crc32val=0xffffffff;
5 printf("len==%d\n",len);
6  for (i = 0;  i  7      crc32val =  crc32_tab[(crc32val ^ s[i]) & 0xff] ^ ((crc32val >> 8)&0x00FFFFFF);
8
9  return ~crc32val;
10}

然后打开VS X64工具命令行提示符,进入到C源码目录,分别执行以下两条命令,第一条命令是生成目标文件.obj,第二天命令是链接目标文件,生成动态库。

1cl /c crc.c
2link /dll crc.obj

至此,dll文件就生成了,它就是我们需要的动态链接库,dll的调用跟so的方法一样。

bf4163e609ef976867d765f7084c664a.png

参考资料

  • https://docs.python.org/3/library/ctypes.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值