Reputation: 3587
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.
Upvotes: 2
Views: 1381
Reputation: 1910
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?
Upvotes: 1