Search code examples
pythondoublectypesadditionsubtraction

How to add/subtract two ctypes.c_double in Python


Simple question. I have two ctypes.c_double. I would like to add or subtract them together.

I want to be able to say something like this:

In [1]: c_double(2) + c_double(2)
Out[1]: c_double(4.0)

Currently, when I try this I get an error: TypeError: unsupported operand type(s) for +: 'c_double' and 'c_double'

My current workaround is this:

In [1]: result = c_double(2).value + c_double(2).value

In [2]: c_double(result)
Out[2]: c_double(4.0)

Is there a way to directly add/subtract ctypes.cdouble?


Solution

  • you could inherit the c_double class to add a __add__ method

    import ctypes
    
    class my_c_double(ctypes.c_double):
        def __add__(self,other):
            return my_c_double(self.value + other.value)
    
    
    a = my_c_double(10)
    b = my_c_double(20)
    
    print((a+b).value)
    

    prints 30

    Note that you may want to implement __radd__ and __iadd__ and check types to be able to directly left add with floats and integers.