python ctypes struct_Python之ctypes

一、Python call C function:

C: vi hello.c

#include

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值