Niklas R
Niklas R

Reputation: 16870

Get address from PyCObject?

I find it really strange that I couldn't an answer to this question by searching, only ever the opposite question on how to create a PyCObject from a pointer (and in C, not Python). I might just have used the wrong search terms.

I have a PyCObject in Python, and I want to get the wrapped memory address. Well, actually I want to convert it to a ctypes pointer, but I can do that from the memory address. How can I get it? help(some_pyc_object) isn't very informative and dir(some_pyc_object) isn't either.

I would like to do the following:

addr = some_pyc_object.get_memory_address()   # pseudo method
data = ctypes.c_long_p(addr)
# ...

Upvotes: 0

Views: 753

Answers (1)

Eryk Sun
Eryk Sun

Reputation: 34270

Call PyCObject_AsVoidPtr:

import ctypes

PyCObject_AsVoidPtr = ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)(
                          ('PyCObject_AsVoidPtr', ctypes.pythonapi))

addr = PyCObject_AsVoidPtr(some_pyc_object)

Upvotes: 3

Related Questions