返回结构时带有ctypes的Segfault - 32位linux

时间:2011-11-29 01:05:45

标签: python linux ctypes

所以我在32位Linux机器上从ctypes获得了一个段错误,我无法在64位darwin或linux上重现。

这是C:

typedef struct {
  void *ptr;
  } doodle;

doodle C_intpointerfunction(int *a)
{
  *a = 41;
  doodle foo;
  foo.ptr = a;
  return foo;
}

编译用:

gcc -c intpointerlibrary.c
gcc -shared intpointerlibrary.o -o libintpointerlib.so

这是Python:

import numpy as N
from ctypes import *

_libintpointer = N.ctypeslib.load_library('libintpointerlib.so','.')

_libintpointer.C_intpointerfunction.restype = c_void_p
_libintpointer.C_intpointerfunction.argtypes = [POINTER(c_int)]
def P_intpointerfunction():
  lrc = c_int(0)
  print "lrc before (should be 0) = "+str(lrc.value)
  return_val = _libintpointer.C_intpointerfunction(byref(lrc))
  print "lrc after (should be 41) = "+str(lrc.value)
  return return_val

现在,当我调用此函数时:

  rc = P_intpointerfunction()

我遇到了段错误。我已经尝试创建一个Python类来包装在C端创建的返回结构,结果相同。如果传回一个本机ctypes类型(如c_int)一切正常..这真的只是一个32位Linux的问题,还是有什么我没有考虑过?谢谢!

1 个答案:

答案 0 :(得分:5)

不确定为什么要设置restype = c_void_p;

class DOODLE(Structure):
    _fields_ = [('ptr', c_void_p)]
_libintpointer.C_intpointerfunction.restype = DOODLE

在Linux x86-64上按预期工作。