2

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?

2 Answers 2

3

You're using a class created by someone else, and it seems that he hasn't written a __add__ method, that handle the '+' operations.

I would suggest you write you're own method :

def add(self, other):
    return c_double(self.value + other.value)

Then you tell the c_double class that add is its __add__ method:

c_double.__add__ = add

I think it should work

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

2 Comments

and it works. You just have to do c_double.__add__ = add in each module where you need addition.
@Jean-FrançoisFabre would you do this in each module's global scope, after from ctypes import c_double?
1

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.

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.