所以我在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端创建的具有相同结果的返回结构。如果传回 native ctypes类型(如c_int),则一切正常。.这确实是32位Linux的问题,还是我没有考虑过?谢谢!

最佳答案

不知道为什么要设置restype = c_void_p;

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

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

10-07 21:10