2

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.

4
  • I think we need to see the use case. Are you wanting to pass the pointer to a 'C' API. Do you have an example of using it? Commented Feb 22, 2018 at 19:28
  • @quamrana Let's say I have this code in C: void bar(void* obj) { printf("%d\n", (int*)obj) }, then I would need to cast data to c_void_p in order to pass it down to this function. Commented Feb 22, 2018 at 19:34
  • Perhaps you mean data = c_void_p(foo.val) if the C function itself is going to recover an int. Commented Feb 22, 2018 at 19:38
  • @quamrana I'm trying to pass in the whole object with multiple attributes, so this method would only work with primitive types. Commented Feb 22, 2018 at 20:10

1 Answer 1

5

Use data = ctypes.py_object(foo).

ctypes.py_object represents the PyObject * type in C.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.