I have been bitten by this twice this week, so I thought I would tell about it:

Contrary to C, C++ has a boolean type, using the same keyword as
Python: "bool". When declaring a C++ function with a (C++) bool
argument, like for example " int myFunc(int val, bool exact)", it
seems logical (although it is not, in insight) to declare it that way:

cdef extern from "xxx.hpp":
     int myFunc(int,bool)

However, cython will understand that "bool" declare a python object of
(python) type bool. Thus, when doing "myFunc(5,False)", myFunc receive
as argument a pointer to the python object "False". And here is the
catch: gcc will implicitly convert this pointer to a C++  "True"
value. After checking, this implicit conversion seems to be part of
the C++ standard.

Therefore, the problem is as follow:
Cython and gcc will emit no warning when a C++ bool is declared by
"bool" in cython. But  when a python "False" is given as an argument
of a C++ function typed by "bool", the C++ function will receive a C++
"true".

Of course, the right way to do it is to declare the C++ bool  as a
"bint". But since the other C/C++ types can be declared by their
normal C names, I think many people will assume that "bool" is the
right keyword here. And since Cython and g++ do not give any warning
about it, this might lead to some slightly puzzling bugs in users
code.

I am not sure you can do something about it  (maybe handle it the same
way that you handle C int and Python int ?). But if you cannot, it
deserves at least a warning in the docs.

(and for the record, although I have been posting quite a lot this
week about bugs and limitations of the c++ mode of cython, I am
overall delighted with it; it works much better and has much more
features than I was expecting when I started using it last week :-)

cheers,
Toki
_______________________________________________
Cython-dev mailing list
Cython-dev@codespeak.net
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to