PYTHON 调用动态库 dll lib.so 使用 ctypes

参考资料:http://www.tech-q.cn/thread-7630-1-1.html

http://docs.python.org/library/ctypes.html#return-types

今天研究了下python调用C的动态库的方法,查阅了相关资料后,发现调用还是很方便的。

 

--------------------------------------------------------------------------------

#!/usr/bin/python

from ctypes import *

def SupportSuff(value):

    if value == 0:

        raise Exception, 'Not support file type.'

    return value

def main():

    #libtest = cdll.LoadLibrary('./libsuffix.so')

    libtest = CDLL('./libsuffix.so')

    get_file_suffix = libtest.get_file_suffix

 # 设定好调用函数的参数类型和返回值类型

     get_file_suffix.argtypes = [POINTER(c_char)]

    get_file_suffix.restype = c_char_p 

    name = 'test.ppt'

    #直接用方法名进行调用

    suff = get_file_suffix(name)

    print suff

    #如果函数的返回值是整数,可以设定其返回属性restype为一个可以调用的函数或类。这样该函数的返回值就是你所指定的函数的结果。

    # 主要用来检查返回值,然后自动抛出异常(其实就是将手动检查返回值改为异常抛出的方式)

    libtest.check_file_suffix.restype = SupportSuff

    ret = libtest.check_file_suffix(suff)

    print ret

 

具体调用代码如上,使用起来也还是比较简单的。还有个问题就是关于内存传递使用的问题。无论是在C里申请内存,在python用;还是python申请内存,在C里使用。

1、在C里申请内存,在py里调用后,需要释放的话 得在py里调用C的释放函数;(我没做过实验,只是在网上找资料的过程中看到有人这样说)

2、在py里申请内存,传递给C去操作,此时的内存释放是不需要去管的,py申请的内存自动由py释放了。

资料:

http://osdir.com/ml/python.ctypes/2005-07/msg00014.html

> Just a quick question I did not see answered in the ctypes tutorial:

> when I create a string buffer, can I assume that python garbage

> collects it, or do I need to call a special method to free it?

>

> p = create_string_buffer("", 254)

>

> #... processing code, finished using p

> # do I need to 'release' p?

You don't have to take a special action. When the last reference from

Python to the string buffer goes away the memory is freed. That's true

for all ctypes instances.

Thomas

其实遇到的很多问题在py的官方文档里都有介绍了,这里有一篇中文翻译的:

http://butlandblog.appspot.com/log-22.html

关于ctypes在文档中也有一些比较特别有意思的地方,如:

注意 这ctypes不包含面向对象,它每次查看一个属性时就创建一个全新的等价的对象。
>>> pi.contents is i
False
>>> pi.contents is pi.contents
False
>>>

具体可在文档中去查询,py作为一个胶水语言,这种调用别的语言的活应该是经常碰到的,应该用熟。

在网上找py的资料的时候发现,质量比较高的提问和回答经常出自CPyUG的Google group邮件列表,虽然得FQ才能访问,不过内容都挺有价值的。

posted @ 2010-10-26 20:57  酷酷的小鱼儿  阅读(2932)  评论(0编辑  收藏  举报