Python在Windows和在Linux下调用动态链接库的教程

yipeiwu_com5年前Python基础

Linux系统下调用动态库(.so)

1、linuxany.c代码如下:

  #include "stdio.h"
  void display(char* msg){
    printf("%s\n",msg);
  }
   
  int add(int a,int b){
    return a+b;
  }

2、编译c代码,最后生成Python可执行的.so文件
(1)gcc -c linuxany.c,将生成一个linuxany.o文件
(2)gcc -shared linuxany.c -o linuxany.so,将生成一个linuxany.so文件

3、在Python中调用

  #!/usr/bin/python
   
  from ctypes import *
  import os 
  //参数为生成的.so文件所在的绝对路径
  libtest = cdll.LoadLibrary(os.getcwd() + '/linuxany.so') 
  //直接用方法名进行调用
  print 
  libtest.display('Hello,I am linuxany.com') 
  print libtest.add(2,2010)

4、运行结果

Hello,I am linuxany.com
2012 


Windows下Python调用dll

python中如果要调用dll,需要用到ctypes模块,在程序开头导入模块 import ctypes

由于调用约定的不同,python调用dll的方法也不同,主要有两种调用规则,即 cdecl和stdcal,还有其他的一些调用约定,关于他们的不同,可以查阅其他资料

先说 stdcal的调用方法:

方法一:

import ctypes
dll = ctypes.windll.LoadLibrary( 'test.dll' )

方法二:

import ctypes
dll = ctypes.WinDll( 'test.dll' )


cdecl的调用方法:

1.

import ctypes
dll = ctypes.cdll.LoadLibrary( 'test.dll' )
##注:一般在linux下为test.o文件,同样可以使用如下的方法:
## dll = ctypes.cdll.LoadLibrary('test.o')

2.

import ctypes
dll = ctypes.CDll( 'test.dll' )

看一个例子,首先编译一个dll

导出函数如下:

# define ADD_EXPORT Q_DECL_EXPORT
extern "C" ADD_EXPORT int addnum(int num1,int num2)
{
return num1+num2;
}


extern "C" ADD_EXPORT void get_path(char *path){
memcpy(path,"hello",sizeof("hello"));
}

这里使用的是cdecl

脚本如下:

dll=ctypes.CDLL("add.dll")
add=dll.addnum
add.argtypes=[ctypes.c_int,ctypes.c_int] #参数类型
add.restypes=ctypes.c_int            #返回值类型
print add(1,2)


get_path=dll.get_path
get_path.argtypes=[ctypes.c_char_p]
path=create_string_buffer(100)
get_path(path)
print path.value

结果如下:

2015818121733886.gif (368×95)

我们看到两个结果,第一个是进行计算,第二个是带回一个参数。

当然我们还可以很方便的使用windows的dll,提供了很多接口

GetSystemDirectory = windll.kernel32.GetSystemDirectoryA
buf = create_string_buffer(100)
GetSystemDirectory(buf,100)
print buf.value
MessageBox = windll.user32.MessageBoxW
MessageBox(None, u"Hello World", u"Hi", 0)

运行结果如下:

2015818121806575.gif (144×160)

相关文章

Python利用Django如何写restful api接口详解

Python利用Django如何写restful api接口详解

前言 用Python如何写一个接口呢,首先得要有数据,可以用我们在网站上爬的数据,在上一篇文章中写了如何用Python爬虫,有兴趣的可以看看:/post/141661.htm 大量的数...

Python类方法__init__和__del__构造、析构过程分析

最近学习《Python参考手册》学到Class部分,遇到了类的构造析构部分的问题: 1、什么时候构造? 2、什么时候析构? 3、成员变量如何处理? 4、Python中的共享成员函数如何访...

Django使用模板后无法找到静态资源文件问题解决

环境配置 Django版本1.11 python版本3.6.2 前言 在编写Django网站的时候,在涉及模板方面,一些简单的例子都没有问题,但这些例子都有一个共同点,那...

Python+pandas计算数据相关系数的实例

本文主要演示pandas中DataFrame对象corr()方法的用法,该方法用来计算DataFrame对象中所有列之间的相关系数(包括pearson相关系数、Kendall Tau相关...

pygame游戏之旅 计算游戏中躲过的障碍数量

pygame游戏之旅 计算游戏中躲过的障碍数量

本文为大家分享了pygame游戏之旅的第8篇,供大家参考,具体内容如下 定义一个计数函数: def things_dodged(count): font = pygame.font...