Python 调用 C 语言的简单流程(一)

在python中调用dll文件,实例代码如下:

1:建立C语言文件,假如名字叫做dlltest.c:

#include "stdlib.h"
__declspec(dllexport)  int __stdcall test( void* p, int len)
{
     return len;
}
编译链接,生成dlltest.dll
注:打开cmd dos窗口,把工作路径调整到dlltext.c所在路径,输入cl -LD dlltest.c -libtest.dll,生成的dlltest.dll也没问题

2:建立python文件,假如名字叫做pyu.py,把下面代码1粘入pyu.py

#代码1
dll = ctypes.windll.LoadLibrary( 'dlltest.dll ')


sBuf = 'abc'
pStr = ctypes.c_char_p( )
pStr.value = sBuf
pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
nRst = dll.test( pVoid, 10 )
print nRst


或者还有一种方式调用dll文件,即用代码2所示方法:
#代码2
import ctypes
from ctypes import *
dll = ctypes.WinDLL( 'dlltest.dll ')


sBuf = 'abc'
pStr = ctypes.c_char_p( )
pStr.value = sBuf
pVoid = ctypes.cast( pStr, ctypes.c_void_p ).value
nRst = dll.test( pVoid, 10 )
print nRst
讲解: ctypes.WinDLL 和 ctypes.windll.LoadLibrary可以互换是因为,ctypes.windll为ctypes.WinDLL类的一个对象


3:运行python文件,搞定


注意:
1)python争取用32位的,生成的dll文件一般情况下都是32为的,64位的python不能支持32位的dll文件;
2)C文件中的函数声明如果是__stdcall或者是__cdcel的话,python中的调用方式一定要对应,要不然也出错,具体方式如下:

#include "stdlib.h"
__declspec(dllexport)  int __cdecl test( void* p, int len)
{
     return len;
}
由于接口中定义的是cdecl格式的调用,所以在python中也需要用相应的类型   
import ctypes 
dll = ctypes.cdll.LoadLibrary( 'dlltest.dll' ) 
import ctypes 
dll = ctypes.CDLL( 'dlltest.dll' ) 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值