歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python Ctypes 結構體指針處理(函數參數,函數返回)

Python Ctypes 結構體指針處理(函數參數,函數返回)

日期:2017/3/1 11:15:10   编辑:Linux編程

C函數需要傳遞結構體指針是常事,但是和Python交互就有點麻煩事了,經過研究也可以了。

<結構體指針作為函數參數>

來看下C測試例子:

  1. #include <stdio.h>
  2. typedef struct StructPointerTest* StructPointer;
  3. struct StructPointerTest{
  4. int x;
  5. int y;
  6. };
  7. void test(StructPointer p) {
  8. p->x = 101;
  9. p->y = 201;
  10. }

這裡test裡面需要傳入結構體指針,函數中的實現很簡單,就是改變x 和 y 的值這個函數將被python調用。

使用Python調用時,需要模擬申明個結構體(class):

  1. from ctypes import *
  2. class StructPointerTest(Structure):
  3. _fields_ =[('x', c_int),
  4. ('y', c_int)]

Usage:

  1. ##Structure Pointer Operation
  2. SPTobj = pointer(StructPointerTest(1, 2))
  3. print SPTobj
  4. print SPTobj.contents.x
  5. print SPTobj.contents.y

<函數返回結構體指針>

C函數測試例子改成如下:

  1. StructPointer test() {
  2. StructPointer p = (StructPointer)malloc(sizeof(struct StructPointerTest));
  3. p->x = 101;
  4. p->y = 201;
  5. return p;
  6. }

Python程序處理如下:

  1. from ctypes import *
  2. class StructPointer(Structure):
  3. pass
  4. StructPointer._fields_=[('x', c_int),
  5. ('y', c_int),
  6. ('next', POINTER(StructPointer))]
  7. lib = cdll.LoadLibrary('./StructPointer.so')
  8. lib.test.restype = POINTER(StructPointer)
  9. p = lib.test()
  10. print p.contents.x
關於resttype可以參見 Tutorial : By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object.
Copyright © Linux教程網 All Rights Reserved