python调用c代码

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

python调用c代码
#!/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调用c代码

python中结构体对应的类型:

python调用c代码
#!/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调用c代码

 

python中Union体对应的类型:

python调用c代码
class _U(Union):
    _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                ("lpadesc", POINTER(ARRAYDESC)),
                ("hreftype", HREFTYPE)]

class TYPEDESC(Structure):
    _anonymous_ = ("u",)
    _fields_ = [("u", _U),
                ("vt", VARTYPE)]
python调用c代码

调用方式

python调用c代码
td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)
python调用c代码

 

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

1、test.c文件

python调用c代码
#include <stdio.h>

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

int main(){
    print_helloworld();
    return 0;
}
python调用c代码

2、生成动态库文件

python调用c代码
gcc -fPIC -c test.c  -o libtest.o
python调用c代码

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

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

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

修改方式如下:

python调用c代码
gcc -fpic -shared -o libtest.o ./test.c 
python调用c代码

3、python调用

python调用c代码
[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!
python调用c代码

 

 参考文献

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

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

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

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

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

python调用c代码,布布扣,bubuko.com

python调用c代码

上一篇:maven web 项目 打入 jar 包 , 和编译入 java 文件到 web-inf 下


下一篇:【C++ Primer】特殊工具与技术