[C++-sig] boost.python: implicit type conversion

Roman Yakovenko roman.yakovenko at gmail.com
Tue Dec 2 19:54:45 CET 2008


On Tue, Dec 2, 2008 at 7:04 PM, Mihail Konstantinov
<kmihail at rocketmail.com> wrote:
> Dear all,
> thanks a lot for your immediate responses that lead to a fast solution for my previous problem.
>
> Here comes the next one.
>
> In the example below both classes A and B are derived from std::string.

It is not a good idea. Python string is immutable. May be you should
consider custom converter.
http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/faq.html#custom_string

>Class B can be implicitly converted to A by means of 'B::operator const A()'. So the function printme(const A&) can also be called with an argument of class B (see main function).
>
> My aim is to be able to call in python:
>>>>import boost_ext
>>>>b=boost_ext.B("hello world")
>>>>boost_ext.printme(b)
> but it produces the error:
>> <class 'Boost.Python.ArgumentError'>: Python argument types in  boost_ext.printme(B)
>> did not match C++ signature:
>>    printme(A)
>
> Can I modify the declaration inside BOOST_PYTHON_MODULE so that the implicit conversion is recognized and the above call boost_ext.printme(b) succeeds?

Yes: http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/implicit.html

> Thank you
> Mihail
>
> BTW, in the code below I'm using a preprocessor definition __BJAM__ which I had to define explicitly in the Jamroot. Is there some variable defined by default which I can use to distinguish between bjam builds and other (testing) calls to g++?

You can separate your source code to different files.


-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/


More information about the Cplusplus-sig mailing list