python调用动态链接库windows_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

脚本如下:

本站所有资源全部来源于网络,若本站发布的内容侵害到您的隐私或者利益,请联系我们删除!

合作方式

Copyright © 2004-2018 https://www.gxlcms.com/. All Rights Reserved.

豫ICP备19030742号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python调用动态可以通过使用ctypes来实现。首先,需要将生成的dll文件复制到Python项目的同一目录下。然后,使用ctypes中的CDLL函数加载dll文件。例如,可以使用以下代码调用名为"demo.dll"的动态中的add函数: ```python import ctypes from ctypes import * mydll = CDLL("./demo.dll") # 一定要有./ 否则无法调用成功 result = mydll.add(1, 2) print(result) ``` 这段代码中,CDLL函数用于加载dll文件,"./demo.dll"表示dll文件的路径。然后,可以通过mydll对象调用dll文件中的函数,例如调用add函数并传入参数1和2。最后,打印函数的返回结果。 #### 引用[.reference_title] - *1* [厉害了,Python也能使用动态](https://blog.csdn.net/pdcfighting/article/details/124549442)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Python调用C/C++之动态(.dll)(vs2019+pycharm)](https://blog.csdn.net/Vccp_1M/article/details/125953351)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值