ctypes使用

有关定义:

(1)__declspec(dllexport)

导出函数,即指明该函数可从DLL中调用

(2)__declspec(dllimport)

导入函数(ctypes尚没有碰到对他的具体应用)

#define EXPORT __declspec(dllexport)
EXPORT int IntAdd(int a, int b)
{
	return a + b;
}

EXPORT char *hello_python()
{
	//char p[] = "hi python, this is c speaking...";
	char *p = "hi python, this is c speaking...";
	return p;
}
先C中写两个函数,以供ctypes调用:

from ctypes import *

filename = 'test_ctypes.dll'
dll = cdll.LoadLibrary(filename)
然后就可以通过dll对象来调用C代码中的“导出函数(__declspec(dllexport))”

intadd = dll.IntAdd
intadd .argtypes设置传入参数的类型

例:addint.argtypes = [c_int, c_int]

intadd .restype设置返回类型

例:addint.restype = c_int

有参数值或者返回值时,应当指明其类型

dll = cdll.LoadLibrary(filename)
addint = dll.IntAdd
addint.argtypes = [c_int, c_int]
addint.restype = c_int
print addint(1,2)#3
print dll.IntAdd(1,2)#3 结果同样也是3,type类型为int,但如果C语言中参数及返回值类型变为了float类型此处就会出现问题

对于只有返回值而没有入参的函数:

只需设定其返回值类型

str_fun = dll.hello_python
str_fun.restype = c_char_p
print str_fun()# hi python, this is c speaking...

ctypes的数据类型映射

ctypes type C type Python Type
c_charchar1-character string
c_wcharwchar_t1-character unicode string
c_bytecharint/long
c_ubyteunsigned charint/long
c_boolboolbool
c_shortshortint/long
c_ushortunsigned shortint/long
c_intintint/long
c_uintunsigned intint/long
c_longlongint/long
c_ulongunsigned longint/long
c_longlong__int64 or longlongint/long
c_ulonglongunsigned __int64 or unsigned long longint/long
c_floatfloatfloat
c_doubledoublefloat
c_longdoublelong double floatfloat
c_char_pchar *string or None
c_wchar_pwchar_t *unicode or None
c_void_pvoid *int/long or None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值