2

Say I have this simple class and instance:

class MyClass:
    def __init__(self, value):
        self.value = value

    def my_method(self):
        return self.value * 2

my_object = MyClass(1)

Is it possible to pass my_object directly to C using ctypes or any other module? If I'm able to get at least the attributes of my_object in C I will be happy, but better If I could get the methods and be able to call them it within C.

I'm currently doing:

import ctypes
my_library = ctypes.CDLL('my_library.so')
my_library.my_c_function.argtypes = [ctypes.c_int]
my_library.my_c_function.restype = ctypes.c_int

my_object_c_value = ctypes.c_int(my_object.value)
my_library.my_c_function(my_object_c_value)

And doing this for every attribute inside my_object. This get's very repetitive when the class has too many attributes.

I tried reading the documentation on ctypes but It's too technical, and incomprehensive for me.

1 Answer 1

1

No, you can't pass pure Python objects to C that way. However, you can declare a ctypes.Structure or ctypes.Union type and pass that to a c function as if it were a C struct or union, usually with a POINTER.

Example from the docs:

from ctypes import *
class POINT(Structure):
    _fields_ = [("x", c_int),
                ("y", c_int)]

point = POINT(10, 20)
...
my_library.my_c_function(POINTER(point))

From your example, though, you are just passing an integer. The ctypes module knows how to map that type without that kind of declaration.

You don't have to declare all your types. That is more for debugging and automatic type casting. You can call your function right after the library is created:

my_library = ctypes.CDLL('my_library.so')
my_library.my_c_function(...)

It is a good idea for debugging to declare the ones you need, though. It isn't that hard to write a small Python program and turn it into a set of declarations like those. I used to load platform include files this way all the time. I like ctypes and use it all the time, but if you want something more brief, maybe you would like "cython" better?

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

3 Comments

That seems pretty succinct. I was wondering if using the C-API is any better, I saw that It have a PyObject for C, but I haven't had any luck using it, I keep getting a bunch of errors.
You can pass a ctypes.py_object, which will hold the global interpreter lock (GIL) for you, but it's usually pointless since you'd need to use the C API anyway.
For using ctypes with a custom class, read the docs for the from_param and _as_parameter_ hooks.

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.