Search code examples
pythoncctypes

Converting Python instance to ctypes.c_void_p


I'm trying to convert a Python object into C void pointer so that it would be callable from C API's, however the following code doesn't seem to work from ctypes import *

class myclass:
    def __init__(self):
        self.val = 6
        return


foo = myclass()

data = c_void_p(foo)

Output:

Traceback (most recent call last):
  File "test.py", line 26, in <module>
    data = c_void_p(foo)
TypeError: cannot be converted to pointer

I've also tried pointer() and byref(), but none of them works. How can I achieve what I'm trying to do? Thanks in advance.


Solution

  • Use data = ctypes.py_object(foo).

    ctypes.py_object represents the PyObject * type in C.