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

#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

结果如下:

509b2dc9ba169e19e8b396f550717ecf.gif

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

当然我们还可以很方便的使用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)

运行结果如下:

b2af693117bc930b8df9a7136bf7a59b.gif

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

相关文章

相关视频

网友评论

文明上网理性发言,请遵守 新闻评论服务协议我要评论

47d507a036d4dd65488c445c0974b649.png

立即提交

专题推荐064df72cb40df78e80e61b7041ee044f.png独孤九贱-php全栈开发教程

全栈 100W+

主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门

7dafe36c040e31d783922649aefe0be1.png玉女心经-web前端开发教程

入门 50W+

主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门

04246fdfe8958426b043c89ded0857f1.png天龙八部-实战开发教程

实战 80W+

主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习

php中文网:公益在线php培训,帮助PHP学习者快速成长!

Copyright 2014-2020 https://www.php.cn/ All Rights Reserved | 苏ICP备2020058653号-1e6cebb680dfe320dad7e62bd6442c3a6.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值