简体   繁体   中英

How do you pass a void * back and forth to a shared library in python using ctypes?

I believe the basic process is:

from ctypes import *

LEAP = ctypes.CDLL('leap.dylib')

leap_controller = LEAP.leap_controller
leap_controller.res_type = c_void_p

leap_controller_dispose = LEAP.leap_controller_dispose
leap_controller_dispose.argtype = [c_void_p]

However, when I invoke this code it mangles the void * pointer. Debugging from the associated C code, I get:

doug:test doug$ python test.py
Controller init!
returning: 0x7fcf9a0022c0
Created controller

Controller dispose!
argument: 0xffffffff9a0022c0
Segmentation fault: 11

Obviously the free() call fails because the pointer isn't right.

I've tried a couple of variations on this, for example, defining a structure, like:

class LEAP_CONTROLLER(Structure):
  _fields_ = [
      ("data", c_void_p)
  ]

leap_controller = LEAP.leap_controller
leap_controller.res_type = POINTER(LEAP_CONTROLLER)

leap_controller_dispose = LEAP.leap_controller_dispose
leap_controller_dispose.argtype = [POINTER(LEAP_CONTROLLER)]

...but the result always seems to be the same.

Python reads the pointer, but only keeps 32 bits worth of data, and returns a broken pointer with the remaining bits all 1.

Both of the binaries are 64 bit:

Non-fat file: /usr/local/bin/python is architecture: x86_64
Non-fat file: ../../dll/libcleap.dylib is architecture: x86_64

I saw this ancient issue, here: http://bugs.python.org/issue1703286

...but it's marked as resolved.

A few other random mailing this threads seem to mention ctypes 'truncating 64-bit pointers to 32-bit', but people all seem to have magically resolved their issues without doing anything ('it works now') or gotten no answer to their questions.

Anyone know what I'm doing wrong?

Answer as per the comments; this was a typo in my code.

 Per the docs, it's argtypes and restype, not argtype and res_type. –  eryksun Oct 4 at 2:31 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM