python调用c代码

Linux环境下使用python调用C的printf例子:

#!/usr/bin/env python2.7
#-*- coding:utf-8 -*-
from ctypes import *
def test():
    #libc = cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")                                                                                                 
msg
= "hello world!\n" libc.printf("Testing:%s",msg) def main(): test() if __name__ == '__main__': main()

python中结构体对应的类型:

#!/usr/bin/env python2.7
#-*- coding:utf-8 -*-
from ctypes import *
class barley_amout(Structure):
    _fields_ = [
        ("barley_long",c_long),
        ("barley_int",c_int),
        ("barley_char",c_char*100)
        ]
def main():
    bu = barley_amout(66,44,"Hello world")
    print bu.barley_long
    print bu.barley_int
    print bu.barley_char

if __name__ == '__main__':
    main()

 

python中Union体对应的类型:

class _U(Union):
    _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                ("lpadesc", POINTER(ARRAYDESC)),
                ("hreftype", HREFTYPE)]

class TYPEDESC(Structure):
    _anonymous_ = ("u",)
    _fields_ = [("u", _U),
                ("vt", VARTYPE)]

调用方式

td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)

 

生成单个so动态库并通过python调用

1、test.c文件

#include <stdio.h>

void print_helloworld(){
    printf("%s","Hello world!\n");
}

int main(){
    print_helloworld();
    return 0;
}

2、生成动态库文件

gcc -fPIC -c test.c  -o libtest.o

通过这种方式在python调用的时候出现

OSError: ./libtest.o: only ET_DYN and ET_EXEC can be loaded

参照这个博客http://xieruilin.iteye.com/blog/730422

修改方式如下:

gcc -fpic -shared -o libtest.o ./test.c 

3、python调用

[root@typhoeus79 20140509]# more call_test.py 
#!/usr/bin/env python2.7
#-*- coding:utf-8 -*-

from ctypes import *
def test():
    libc = CDLL("./libtest.o")
    libc.print_helloworld()

if __name__ == '__main__':
    test()
[root@typhoeus79 20140509]# ./call_test.py    
Hello world!

 

 参考文献

https://docs.python.org/2/library/ctypes.html?highlight=structure#ctypes.Structure

https://docs.python.org/2.7/library/ctypes.html#module-ctypes

http://chimera.labs.oreilly.com/books/1230000000393/ch15.html#_solution_240

http://wangrqa.blog.163.com/blog/static/170946827201010309510247/

http://csl.name/C-functions-from-Python/

http://mypyg.iteye.com/blog/845915

posted @ 2014-05-09 15:20  小郭学路  阅读(1019)  评论(0编辑  收藏  举报