[C++-sig] Re: implicitly_convertible and char*

David Abrahams dave at boost-consulting.com
Tue Jun 29 17:54:55 CEST 2004


Dusty Leary <dleary at gmail.com> writes:

> full source code:
> ================================================
> #define BOOST_PYTHON_STATIC_LIB
>
> #include <boost/python.hpp>
> using namespace boost::python;
>
> struct X {
>     std::string v;
>     X(const std::string& s) : v(s) {}
>     operator char*() const { return (char*)v.c_str(); }
> };
>
> void test_x(X& x) {
>     char* x_string = x;
>     printf("test_x: %s\n", x_string);
> }
>
> void test_string(char* s) {
>     printf("test_string: %s\n", s);
> }

Oh!

char* is not a C++ string, and there's no built-in converter for that.
I note that you're casting away the const-ness of v.c_str() above;
that's very bad juju.  If you make char* into char const* everywhere,
your example should work.  Alternatively, you can also register a
custom from_python converter for char*... but I recommend against it.

>
> BOOST_PYTHON_MODULE(test_string) {
>     class_<X>("X", init<const std::string&>());
>     def("test_x", test_x);
>     def("test_string", test_string);
>     implicitly_convertible<X, char*>();
> }
> ================================================
>
> interpreter:
>
>>>> import test_string
>>>> x = test_string.X("foo")
>>>> test_string.test_x(x)
> test_x: foo
>>>> test_string.test_string("blah")
> test_string: blah
>>>> test_string.test_string(x)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> Boost.Python.ArgumentError: Python argument types in
>     test_string.test_string(X)
> did not match C++ signature:
>     test_string(char *)

-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com





More information about the Cplusplus-sig mailing list