Python之ctypes

一、Python call C function:

C: vi hello.c

#include <stdio.h>

void print_hello()
{
printf("hello world\n");
}

  

gcc -fPIC -shared -o libhello.so

Python: vi test.py

import ctypes

func = ctypes.CDLL("libhello.so")

func.print_hello()

  

二:Ctypes 结构体

1. 定义结构体:

class My_ST( Structure )
    _fields_ = [
        ( 'x', c_int ),
        ( 'y', c_int ),

   ('z', c_char*16)]

2. 传递结构体:

_local = My_ST( 1, 2,"saaa" )
dealwith_struct( byref( _local ))   #byref means get pointer.

注意:这里如果C里面是二维数组例如aa[4][5], 这里Ctypes还没有更好办法。

3. Python返回字符串

void char * TestTest (void)
{
    return "Hello!";
}

在Python中可以这样调用:

import ctypes
dll = ctypes.CDLL('Test.dll')
rst = dll.TestTest()
print(rst)     # there rst is a point.
size = -1
rst = ctypes.string_at(rst, size)
print(rst)

  

 

posted @ 2016-08-05 22:02  JustRelax  阅读(354)  评论(0编辑  收藏  举报