From amohr at pixar.com Wed Nov 1 19:02:41 2006 From: amohr at pixar.com (Alex Mohr) Date: Wed, 01 Nov 2006 10:02:41 -0800 Subject: [C++-sig] Supplying a Python base class when wrapping a C++ class... Message-ID: <4548E141.8030206@pixar.com> I'd like to wrap a C++ class and have the generated python wrapper class derive from a Python class. I know I can use bases<> to have my wrapped class derive from the class objects associated with the C++ types I specify in bases<>, but in this instance, I want to derive my wrapper class from a Python class that was not generated by boost.python. From looking at the code, it seems like it would be some work to add this capability. (Is anyone working on something like this?) As a workaround, does anyone know a way that I could perhaps hack this in after the Python class is created? That is, can I change the Python base classes of a Python class at runtime? Thanks, Alex From seefeld at sympatico.ca Wed Nov 1 19:22:31 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 01 Nov 2006 13:22:31 -0500 Subject: [C++-sig] Supplying a Python base class when wrapping a C++ class... In-Reply-To: <4548E141.8030206@pixar.com> References: <4548E141.8030206@pixar.com> Message-ID: <4548E5E7.6020606@sympatico.ca> Alex Mohr wrote: > I'd like to wrap a C++ class and have the generated python wrapper class > derive from a Python class. > > I know I can use bases<> to have my wrapped class derive from the class > objects associated with the C++ types I specify in bases<>, but in this > instance, I want to derive my wrapper class from a Python class that was > not generated by boost.python. > > From looking at the code, it seems like it would be some work to add > this capability. (Is anyone working on something like this?) > > As a workaround, does anyone know a way that I could perhaps hack this > in after the Python class is created? That is, can I change the Python > base classes of a Python class at runtime? I believe this depends on what you are trying to accomplish. You can certainly derive a new python class from both, the python wrapper for your C++ class, as well as some other python class. I don't think it's possible to make the generated wrapper itself be derived from a particular python base class (other than 'object'). This is because all wrappers have a common metaclass, provided by boost.python, and python puts some constraints on the relationship between metaclasses of derived types. But multiple inheritance should be able to help. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From amohr at pixar.com Wed Nov 1 19:35:36 2006 From: amohr at pixar.com (Alex Mohr) Date: Wed, 01 Nov 2006 10:35:36 -0800 Subject: [C++-sig] Supplying a Python base class when wrapping a C++ class... In-Reply-To: <4548E5E7.6020606@sympatico.ca> References: <4548E141.8030206@pixar.com> <4548E5E7.6020606@sympatico.ca> Message-ID: <4548E8F8.1090205@pixar.com> > I believe this depends on what you are trying to accomplish. You can > certainly derive a new python class from both, the python wrapper for > your C++ class, as well as some other python class. Sure, but then can I replace the registration that boost.python has for the type that I wrapped with my new class? To be a bit more concrete: class_ >(...); // Build a new python class that derives from the python class for Foo // that boost.python generated AND derives from another Python class. // Now I need to replace boost.python's notion of the python class // associated with Foo to be the multiply-derived python class I just // made. > I don't think it's possible to make the generated wrapper itself be > derived from a particular python base class (other than 'object'). > This is because all wrappers have a common metaclass, provided by boost.python, > and python puts some constraints on the relationship between metaclasses > of derived types. Well, but you do make it derive from bases other than 'object' by supplying bases -- boost.python looks up python classes associated with X, Y, and Z, and derives the new python wrapper class from those python bases. The problem is that I can only specify bases with compile-time type template parameters -- I can't pass arbitrary python classes. Thanks for the info, Alex From seefeld at sympatico.ca Wed Nov 1 19:56:19 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 01 Nov 2006 13:56:19 -0500 Subject: [C++-sig] Supplying a Python base class when wrapping a C++ class... In-Reply-To: <4548E8F8.1090205@pixar.com> References: <4548E141.8030206@pixar.com> <4548E5E7.6020606@sympatico.ca> <4548E8F8.1090205@pixar.com> Message-ID: <4548EDD3.9060103@sympatico.ca> Alex Mohr wrote: >> I believe this depends on what you are trying to accomplish. You can >> certainly derive a new python class from both, the python wrapper for >> your C++ class, as well as some other python class. > > Sure, but then can I replace the registration that boost.python has for > the type that I wrapped with my new class? To be a bit more concrete: > > class_ >(...); > > // Build a new python class that derives from the python class for Foo > // that boost.python generated AND derives from another Python class. OK. > // Now I need to replace boost.python's notion of the python class > // associated with Foo to be the multiply-derived python class I just > // made. Why ? >> I don't think it's possible to make the generated wrapper itself be >> derived from a particular python base class (other than 'object'). >> This is because all wrappers have a common metaclass, provided by boost.python, >> and python puts some constraints on the relationship between metaclasses >> of derived types. > > Well, but you do make it derive from bases other than 'object' by > supplying bases -- boost.python looks up python classes > associated with X, Y, and Z, and derives the new python wrapper class > from those python bases. Sure. But all these bases get exposed to python the same way, using the very same metaclass. > The problem is that I can only specify bases > with compile-time type template parameters -- I can't pass arbitrary > python classes. Indeed. I was talking about multiple inheritance within python, not by means of bases<...>. Sorry if that wasn't clear. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From amohr at pixar.com Wed Nov 1 20:26:08 2006 From: amohr at pixar.com (Alex Mohr) Date: Wed, 01 Nov 2006 11:26:08 -0800 Subject: [C++-sig] Supplying a Python base class when wrapping a C++ class... In-Reply-To: <4548EDD3.9060103@sympatico.ca> References: <4548E141.8030206@pixar.com> <4548E5E7.6020606@sympatico.ca> <4548E8F8.1090205@pixar.com> <4548EDD3.9060103@sympatico.ca> Message-ID: <4548F4D0.3080305@pixar.com> >> class_ >(...); >> >> // Build a new python class that derives from the python class for Foo >> // that boost.python generated AND derives from another Python class. > > OK. > >> // Now I need to replace boost.python's notion of the python class >> // associated with Foo to be the multiply-derived python class I just >> // made. > > Why ? So that when boost.python converts a Foo to-python it generates a wrapper that derives from the extra class that I want it to. Also, so when someone invokes Foo's constructor in python, they get an object that has the bases I desire. I mean, I really want the wrapper for Foo to derive from this other Python class. > Indeed. I was talking about multiple inheritance within python, > not by means of bases<...>. Sorry if that wasn't clear. Sure, but in some sense it's the same thing -- when I say class_, boost.python just uses the python C api to build a wrapper class (which derives from the wrapper classes for the types I specified in bases<>). I just want to provide an extra base class. Alex From dave at boost-consulting.com Fri Nov 3 15:31:51 2006 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 03 Nov 2006 09:31:51 -0500 Subject: [C++-sig] Supplying a Python base class when wrapping a C++ class... References: <4548E141.8030206@pixar.com> Message-ID: <87fyd0bnzc.fsf@pereiro.luannocracy.com> Alex Mohr writes: > I'd like to wrap a C++ class and have the generated python wrapper class > derive from a Python class. > > I know I can use bases<> to have my wrapped class derive from the class > objects associated with the C++ types I specify in bases<>, but in this > instance, I want to derive my wrapper class from a Python class that was > not generated by boost.python. > > From looking at the code, it seems like it would be some work to add > this capability. (Is anyone working on something like this?) That feature has been on my mental TODO list for a long time. Last time I looked, it was implementable. > As a workaround, does anyone know a way that I could perhaps hack this > in after the Python class is created? That is, can I change the Python > base classes of a Python class at runtime? I'm not sure about that. -- Dave Abrahams Boost Consulting www.boost-consulting.com From viznut at charter.net Fri Nov 3 16:46:19 2006 From: viznut at charter.net (Randall Hopper) Date: Fri, 3 Nov 2006 09:46:19 -0600 Subject: [C++-sig] Type conversion problem In-Reply-To: <20061103153441.GA7425@charter.net> References: <20061103153441.GA7425@charter.net> Message-ID: <20061103154619.GA7592@charter.net> Left out a useful piece: Randall Hopper: |and here's a piece of the referenced template: | | using namespace boost::python; | | template | class TemplateCompArray | { | public : | TemplateCompArray(const char * name) : _array(name, boost::python::no_init) { | _array | .def(init<>()) | .def(init()) | .def("__init__", make_constructor(&create_from_tuple)) | .def("getNumElements", &T::getNumElements) | .def("__getitem__", &getitem, return_internal_reference<>()) | .def("__setitem__", &setitem, return_internal_reference<>()) | .def("resize", &resize) | .def("__str__", &str) | ... | static std::string str(T * self) | { | ... | } private: class_, bases, boost::noncopyable> _array; | } I guess I've been perplexed a bit by the boost syntax and not knowing how the boost templates expand and what that does to the type structure. But I'm starting to suspect that some sort of type redirection is required since the actual boost-wrapped array is a private member of the registered class. I'm I even close? Thanks, Randall From beau.sapach at ualberta.ca Fri Nov 3 19:27:52 2006 From: beau.sapach at ualberta.ca (Beau Sapach) Date: Fri, 3 Nov 2006 11:27:52 -0700 Subject: [C++-sig] Passing an instance... Message-ID: <000501c6ff75$c85b4900$5911db00$@sapach@ualberta.ca> Hello everyone, I've got a C++ object that I've created a Python type for. When I insert the object into the main module using PyModule_AddObject then I can instantiate it in Python and everything works just fine. I assumed (mostly from reading other's code) that I could use something like: PyDict_SetItemString(MainDict,"x",pMyObject) To get a variable called "x" into my python environment that IS the same instance as that pointed to by pMyObject. Then by running PyRun_SimpleString("x.somefunction()\n") I could make use of pMyObject from within Python. This doesn't work, my application crashes. What is the best way to accomplish this using the Py??? functions from the Python API? Beau -------------- next part -------------- An HTML attachment was scrubbed... URL: From viznut at charter.net Fri Nov 3 16:34:41 2006 From: viznut at charter.net (Randall Hopper) Date: Fri, 3 Nov 2006 09:34:41 -0600 Subject: [C++-sig] Type conversion problem Message-ID: <20061103153441.GA7425@charter.net> I'm trying to update the PyOSG wrappers to allow access to an array type returned from a C++ class method. All attempts to call a Python method on the returned array or it's elements (even print it), result in a Boost.Python.ArgumentError (error msg at bottom). Here's the wrap of the array class (osg::Vec3Array): namespace PyOSG { void init_ArrayVec3() { TemplateCompArray Vec3Array("Vec3Array"); } } and here's a piece of the referenced template: using namespace boost::python; template class TemplateCompArray { public : TemplateCompArray(const char * name) : _array(name, boost::python::no_init) { _array .def(init<>()) .def(init()) .def("__init__", make_constructor(&create_from_tuple)) .def("getNumElements", &T::getNumElements) .def("__getitem__", &getitem, return_internal_reference<>()) .def("__setitem__", &setitem, return_internal_reference<>()) .def("resize", &resize) .def("__str__", &str) ... static std::string str(T * self) { ... } } Any idea why printing (or calling a Python method of the wrapped Vec3Array in Python should generate a type error? It's like boost.python doesn't realize the TemplateCompArray instantiation "is" Vec3Array. Thanks, Randall P.S. If you want to see the full source for context, check out: http://mosca.caltech.edu/pyosg_downloads/pyosg_ads_15.tar.gz and look in osg/ArrayVec3.cpp and include/TemplateCompArray.hpp. ------------------------------------------------------------------------------ Traceback (most recent call last): ... File "osg_to_sgg.py", line 147, in setupGeode print geom.getVertexArray() Boost.Python.ArgumentError: Python argument types in Vec3Array.__str__(Vec3Array) did not match C++ signature: __str__(osg::TemplateArray*) From seefeld at sympatico.ca Fri Nov 3 20:11:27 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Fri, 03 Nov 2006 14:11:27 -0500 Subject: [C++-sig] Passing an instance... In-Reply-To: <000501c6ff75$c85b4900$5911db00$@sapach@ualberta.ca> References: <000501c6ff75$c85b4900$5911db00$@sapach@ualberta.ca> Message-ID: <454B945F.9010905@sympatico.ca> Beau Sapach wrote: > Hello everyone, > > > > I've got a C++ object that I've created a Python type for. When I insert > the object into the main module using PyModule_AddObject then I can > instantiate it in Python and everything works just fine. I assumed (mostly > from reading other's code) that I could use something like: > > > > PyDict_SetItemString(MainDict,"x",pMyObject) Up to this point there is no need to use the C API directly. Assuming you have exported your C++ type 'Type' to python, you can write (inside C++): namespace bpl = boost::python; bpl::object instance(Type(...)); bpl::dict global; global["instance"] = instance; bpl::exec_file(python_script, global, global); and the executed script can access your Type instance directly through the 'instance' variable. Caution: the 'exec_file' function has been added after 1.33.1, so you need to use a CVS snapshot. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From beau.sapach at ualberta.ca Fri Nov 3 20:57:23 2006 From: beau.sapach at ualberta.ca (Beau Sapach) Date: Fri, 3 Nov 2006 12:57:23 -0700 Subject: [C++-sig] Passing an instance... In-Reply-To: <454B945F.9010905@sympatico.ca> References: <000501c6ff75$c85b4900$5911db00$@sapach@ualberta.ca> <454B945F.9010905@sympatico.ca> Message-ID: <001201c6ff82$47b392a0$d71ab7e0$@sapach@ualberta.ca> Hi Stefan, Yes.... I originally got a copy of this code (and the recommendation to move to the CVS version) from you via this list. When I last left boost, using your example code, the library was crashing on: bpl::object main = python::import("__main__"); as I was trying to add my instance to the main module's dictionary. Because of that I've abandoned boost for the time being and am trying to simply understand the C API better. I suppose I could look into the boost::python code to see what operator[] is doing but I was hoping a quick answer from the mailing list would point me in the right direction, with either the correct API function or telling me what I'm missing. Beau -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Stefan Seefeld Sent: Friday, November 03, 2006 12:11 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Passing an instance... Beau Sapach wrote: > Hello everyone, > > > > I've got a C++ object that I've created a Python type for. When I > insert the object into the main module using PyModule_AddObject then I > can instantiate it in Python and everything works just fine. I > assumed (mostly from reading other's code) that I could use something like: > > > > PyDict_SetItemString(MainDict,"x",pMyObject) Up to this point there is no need to use the C API directly. Assuming you have exported your C++ type 'Type' to python, you can write (inside C++): namespace bpl = boost::python; bpl::object instance(Type(...)); bpl::dict global; global["instance"] = instance; bpl::exec_file(python_script, global, global); and the executed script can access your Type instance directly through the 'instance' variable. Caution: the 'exec_file' function has been added after 1.33.1, so you need to use a CVS snapshot. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig From viznut at charter.net Fri Nov 3 16:34:42 2006 From: viznut at charter.net (Randall Hopper) Date: Fri, 3 Nov 2006 09:34:42 -0600 Subject: [C++-sig] Type conversion problem Message-ID: <20061103153441.GA7425@charter.net> I'm trying to update the PyOSG wrappers to allow access to an array type returned from a C++ class method. All attempts to call a Python method on the returned array or it's elements (even print it), result in a Boost.Python.ArgumentError (error msg at bottom). Here's the wrap of the array class (osg::Vec3Array): namespace PyOSG { void init_ArrayVec3() { TemplateCompArray Vec3Array("Vec3Array"); } } and here's a piece of the referenced template: using namespace boost::python; template class TemplateCompArray { public : TemplateCompArray(const char * name) : _array(name, boost::python::no_init) { _array .def(init<>()) .def(init()) .def("__init__", make_constructor(&create_from_tuple)) .def("getNumElements", &T::getNumElements) .def("__getitem__", &getitem, return_internal_reference<>()) .def("__setitem__", &setitem, return_internal_reference<>()) .def("resize", &resize) .def("__str__", &str) ... static std::string str(T * self) { ... } } Any idea why printing (or calling a Python method of the wrapped Vec3Array in Python should generate a type error? It's like boost.python doesn't realize the TemplateCompArray instantiation "is" Vec3Array. Thanks, Randall P.S. If you want to see the full source for context, check out: http://mosca.caltech.edu/pyosg_downloads/pyosg_ads_15.tar.gz and look in osg/ArrayVec3.cpp and include/TemplateCompArray.hpp. ------------------------------------------------------------------------------ Traceback (most recent call last): ... File "osg_to_sgg.py", line 147, in setupGeode print geom.getVertexArray() Boost.Python.ArgumentError: Python argument types in Vec3Array.__str__(Vec3Array) did not match C++ signature: __str__(osg::TemplateArray*) From viznut at charter.net Sat Nov 4 01:41:30 2006 From: viznut at charter.net (Randall Hopper) Date: Fri, 3 Nov 2006 18:41:30 -0600 Subject: [C++-sig] Type conversion problem -- simplified In-Reply-To: <20061103154619.GA7592@charter.net> References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> Message-ID: <20061104004130.GA11924@charter.net> I've been digging into this and can summarize the problem more succinctly now (I was barking up the wrong tree before). What do I need to do to tell boost::python to dereference a wrapped C++ pointer before trying to invoke the C++ class instance's methods? I've got a method returning a pointer to a C++ class instance, and right now I can't use it as a callable because boost::python treats it like a pointer. Traceback (most recent call last): ... File "osg_to_sgg.py", line 153, in setupGeode v[0].set( 0, 1, 2 ) Boost.Python.ArgumentError: Python argument types in Vec3Array.__getitem__(Vec3Array, int) did not match C++ signature: __getitem__(osg::TemplateArray*, int) Note that the Vec3Array type is identical to the osg::TemplateArray<...> type (via typedef), so the key difference is the extra "*" in the last line. Thanks, Randall From roman.yakovenko at gmail.com Sat Nov 4 07:29:03 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Sat, 4 Nov 2006 08:29:03 +0200 Subject: [C++-sig] Type conversion problem -- simplified In-Reply-To: <20061104004130.GA11924@charter.net> References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> Message-ID: <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> On 11/4/06, Randall Hopper wrote: > I've been digging into this and can summarize the problem more > succinctly now (I was barking up the wrong tree before). > > What do I need to do to tell boost::python to dereference a wrapped > C++ pointer before trying to invoke the C++ class instance's methods? > > I've got a method returning a pointer to a C++ class instance, and > right now I can't use it as a callable because boost::python treats it like > a pointer. > > Traceback (most recent call last): > ... > File "osg_to_sgg.py", line 153, in setupGeode > v[0].set( 0, 1, 2 ) > Boost.Python.ArgumentError: Python argument types in > Vec3Array.__getitem__(Vec3Array, int) > did not match C++ signature: > __getitem__(osg::TemplateArray*, int) > > Note that the Vec3Array type is identical to the osg::TemplateArray<...> > type (via typedef), so the key difference is the extra "*" in the last > line. I don't think anyone is able to follow you. In my opinion, you'd better create one message with clear description of the problem + small test case that reproduces the problem. Take into account, that most of the people here do not know what is osg. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From richardb at avisynth.org Sat Nov 4 09:40:23 2006 From: richardb at avisynth.org (Richard Berg) Date: Sat, 4 Nov 2006 03:40:23 -0500 Subject: [C++-sig] Boost::Python patch for decorated class method In-Reply-To: <49448090A2EE704A8F09D215BE423C8B8E1A9E@ntxbeus04.exchange.xchg> References: <49448090A2EE704A8F09D215BE423C8B8E1A9E@ntxbeus04.exchange.xchg> Message-ID: <000b01c6ffec$de9e0320$6e01a8c0@yakko> Nobody wants to fix this? -----Original Message----- From: Richard Berg [mailto:richardb at avisynth.org] Sent: Thursday, October 26, 2006 1:28 AM To: c++-sig at python.org Subject: RE: Boost::Python patch for decorated class method Surprised there was no response from Boost. Is this the right place to submit boost::python bugs & patches? -----Original Message----- From: Richard Berg [mailto:richardb at avisynth.org] Sent: Sunday, October 15, 2006 21:40 To: boost at lists.boost.org Subject: Boost::Python patch for decorated class method I found that I could not compile any code that tried to export a class method to Python if the method was "decorated" with a calling convention like __cdecl (MSVC8 style).? Standalone functions work ok because the compiler matches them against RT(*) while class methods were trying to match against RT(ClassT::*). ? I'm sure there's a concise way to make signature.hpp work with decorative keywords generally, so I am *not* proposing you accept my patch.? I know virtually nothing about template metaprogramming; my code is neither concise nor general.? However, the patch does demonstrate the problem and solution. ? Best, -Richard From viznut at charter.net Sat Nov 4 16:21:27 2006 From: viznut at charter.net (Randall Hopper) Date: Sat, 4 Nov 2006 09:21:27 -0600 Subject: [C++-sig] Type conversion problem -- simplified In-Reply-To: <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> Message-ID: <20061104152127.GA16288@charter.net> Roman Yakovenko: |Randall Hopper; |> What do I need to do to tell boost::python to dereference a wrapped |> C++ pointer before trying to invoke the C++ class instance's methods? | |I don't think anyone is able to follow you. Thanks for the candid reply. I thought I had a simple question, but I'll see what I can do about thining this down to a simple example. The problem is I'm trying to fix someone else's wrappers, and after hours reading the boost docs and playing with this problem, I don't understand the fundamentals of boost enough to "get under the hood" (dump the compiler output, and trace metaprogramming templates). Despite the selling point, boost "does" require it's own metalanguage, and it's as confusing as hell to the newbie that needs to leave the yellow brick road of: .def( "f", &f, "Hi mom" ) I really do want to become skilled at boost, so I'd greatly appreciate it if you'd point me at 5-10 URLs to read in order (in case I haven't already read them). As far as experience level, I'm an accomplished C++ programmer (15+ years), but I don't usually use templates to solve problems because in C++ they often obfuscate more than they simplify. I'm willing to delve in though. |In my opinion, you'd better create one message with clear description of |the problem + small test case that reproduces the problem. Take into |account, that most of the people here do not know what is osg. Sorry, it's not that relevent but "osg" is the namespace prefix used by OpenSceneGraph (www.openscenegraph.org). The boost::python wrappers for OpenSceneGraph I'm working on are here: http://mosca.caltech.edu/pyosg_downloads/pyosg_ads_15.tar.gz Thanks, Randall From dave at boost-consulting.com Sat Nov 4 22:08:27 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 04 Nov 2006 16:08:27 -0500 Subject: [C++-sig] Type conversion problem -- simplified References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> Message-ID: <87odrmhqd0.fsf@pereiro.luannocracy.com> Randall Hopper writes: > I've been digging into this and can summarize the problem more > succinctly now (I was barking up the wrong tree before). > > What do I need to do to tell boost::python to dereference a wrapped > C++ pointer wrapped how? > before trying to invoke the C++ class instance's methods? Normally -- if you've exposed a C++ class X to Python with class_("PyX") -- when you ask Boost.Python to convert an X* to Python, it complains because it doesn't know whether and how to manage the lifetime of the referenced X object. Normally one uses a CallPolicy (http://tinyurl.com/yjt72m#python.call_policies) to describe how the pointer should be handled. Specifically, it's usually an return_value_policy where R is a ResultConverterGenerator (http://tinyurl.com/ydmvuf#result_converter_generators) such as manage_new_object. Once you've succeeded in making the conversion, what you end up with on the Python side is just a PyX object that happens to get to the X instance through that pointer, and operations on the converted X* work just the same as if you had converted an X object directly to Python. > I've got a method returning a pointer to a C++ class instance, and > right now I can't use it as a callable because boost::python treats it like > a pointer. I don't think that's the problem. > > Traceback (most recent call last): > ... > File "osg_to_sgg.py", line 153, in setupGeode > v[0].set( 0, 1, 2 ) > Boost.Python.ArgumentError: Python argument types in > Vec3Array.__getitem__(Vec3Array, int) __getitem__ refers to the square brackets operator, so this has nothing to do with callability of the Vec3Array object. > did not match C++ signature: > __getitem__(osg::TemplateArray*, int) > Note that the Vec3Array type is identical to the osg::TemplateArray<...> > type (via typedef), so the key difference is the extra "*" in the last > line. Interesting; how did you generate that __getitem__ method? Its first parameter should be a reference to a Vec3Array, not a pointer. -- Dave Abrahams Boost Consulting www.boost-consulting.com From dave at boost-consulting.com Sat Nov 4 22:12:38 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 04 Nov 2006 16:12:38 -0500 Subject: [C++-sig] Type conversion problem -- simplified References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> <20061104152127.GA16288@charter.net> Message-ID: <87irhuhq61.fsf@pereiro.luannocracy.com> Randall Hopper writes: > Roman Yakovenko: > |Randall Hopper; > |> What do I need to do to tell boost::python to dereference a wrapped > |> C++ pointer before trying to invoke the C++ class instance's methods? > | > |I don't think anyone is able to follow you. > > Thanks for the candid reply. I thought I had a simple question, but I'll > see what I can do about thining this down to a simple example. This should be pretty simple. > The problem is I'm trying to fix someone else's wrappers, and after hours > reading the boost docs and playing with this problem, I don't understand > the fundamentals of boost enough to "get under the hood" (dump the compiler > output, and trace metaprogramming templates). Why in anyone's name would you want to do that? > Despite the selling point, boost "does" require it's own > metalanguage, and it's as confusing as hell to the newbie that needs > to leave the yellow brick road of: > > .def( "f", &f, "Hi mom" ) > > I really do want to become skilled at boost, so I'd greatly > appreciate it if you'd point me at 5-10 URLs to read in order (in > case I haven't already read them). As far as experience level, I'm > an accomplished C++ programmer (15+ years), but I don't usually use > templates to solve problems because in C++ they often obfuscate more > than they simplify. I think you're scapegoating the technology; the information needed to debug your problem was in your previous message; it has nothing to do with metaprogramming or templates. -- Dave Abrahams Boost Consulting www.boost-consulting.com From dave at boost-consulting.com Sat Nov 4 22:19:57 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 04 Nov 2006 16:19:57 -0500 Subject: [C++-sig] Type conversion problem -- simplified References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <87odrmhqd0.fsf@pereiro.luannocracy.com> Message-ID: <87d582hptu.fsf@pereiro.luannocracy.com> David Abrahams writes: >> Traceback (most recent call last): >> ... >> File "osg_to_sgg.py", line 153, in setupGeode >> v[0].set( 0, 1, 2 ) >> Boost.Python.ArgumentError: Python argument types in >> Vec3Array.__getitem__(Vec3Array, int) > > __getitem__ refers to the square brackets operator, so this has > nothing to do with callability of the Vec3Array object. > >> did not match C++ signature: >> __getitem__(osg::TemplateArray*, int) >> Note that the Vec3Array type is identical to the osg::TemplateArray<...> >> type (via typedef), so the key difference is the extra "*" in the last >> line. > > Interesting; how did you generate that __getitem__ method? Its first > parameter should be a reference to a Vec3Array, not a pointer. Come to think of it, the reason we prefer a reference is that wrapped C++ functions with pointer parameters will accept a wrapped NULL pointer, and those accepting a reference parameter will automatically reject a NULL pointer at the library level, saving the function author from the NULL check. So the signature of the function wrapped to generate that __getitem__ method above is *more* permissive than if it was built in the usual correct manner. If you're certain that osg::TemplateArray and Vec3Array are identical types, then I'm stumped. I'd like to see the code that exposes Vec3Array to Python. But even more than that, I'd like to see a minimal, reproducible example of your problem. -- Dave Abrahams Boost Consulting www.boost-consulting.com From dave at boost-consulting.com Sat Nov 4 22:21:25 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 04 Nov 2006 16:21:25 -0500 Subject: [C++-sig] Boost::Python patch for decorated class method References: <49448090A2EE704A8F09D215BE423C8B8E1A9E@ntxbeus04.exchange.xchg> <000b01c6ffec$de9e0320$6e01a8c0@yakko> Message-ID: <877iyahpre.fsf@pereiro.luannocracy.com> "Richard Berg" writes: > Nobody wants to fix this? Of course, it's just a matter of finding time. If you can submit a complete patch with docs (if any are needed) and tests, of course, it would be easier. > -----Original Message----- > From: Richard Berg [mailto:richardb at avisynth.org] > Sent: Thursday, October 26, 2006 1:28 AM > To: c++-sig at python.org > Subject: RE: Boost::Python patch for decorated class method > > Surprised there was no response from Boost. Is this the right place to > submit boost::python bugs & patches? > > -----Original Message----- > From: Richard Berg [mailto:richardb at avisynth.org] > Sent: Sunday, October 15, 2006 21:40 > To: boost at lists.boost.org > Subject: Boost::Python patch for decorated class method > > I found that I could not compile any code that tried to export a class > method to Python if the method was "decorated" with a calling convention > like __cdecl (MSVC8 style).? Standalone functions work ok because the > compiler matches them against RT(*) while class methods were trying to match > against RT(ClassT::*). > ? > I'm sure there's a concise way to make signature.hpp work with decorative > keywords generally, so I am *not* proposing you accept my patch.? I know > virtually nothing about template metaprogramming; my code is neither concise > nor general.? However, the patch does demonstrate the problem and solution. > ? > Best, > -Richard -- Dave Abrahams Boost Consulting www.boost-consulting.com From viznut at charter.net Sun Nov 5 00:17:44 2006 From: viznut at charter.net (Randall Hopper) Date: Sat, 4 Nov 2006 17:17:44 -0600 Subject: [C++-sig] Type conversion problem -- simplified In-Reply-To: <87d582hptu.fsf@pereiro.luannocracy.com> <87irhuhq61.fsf@pereiro.luannocracy.com> <87odrmhqd0.fsf@pereiro.luannocracy.com> References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> <20061104152127.GA16288@charter.net> <87irhuhq61.fsf@pereiro.luannocracy.com> <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <87odrmhqd0.fsf@pereiro.luannocracy.com> Message-ID: <20061104231744.GA20294@charter.net> David Abrahams: |> What do I need to do to tell boost::python to dereference a wrapped |> C++ pointer before trying to invoke the C++ class instance's methods? | |Specifically, it's usually an return_value_policy where R is a |ResultConverterGenerator such as manage_new_object. | |Once you've succeeded in making the conversion, what you end up with |on the Python side is just a PyX object that happens to get to the X |instance through that pointer, and operations on the converted X* work |just the same as if you had converted an X object directly to Python. Thanks for the reply, Dave. This code does use a return policy ("manage_osg_object", specifically), as this C++ package uses its own ref counting: http://mosca.caltech.edu/pyosg_downloads/pyosg_ads_15.tar.gz Off and on today, I've been paring this package down to the absolute minimum needed to reproduce the problem so it hopefully will take less than a minute of someone's time to point out what I'm missing. I hope to post that soon. I'm determined to get to the bottom of this. For what boost::python does do when merely given function pointer, it is "truly" amazing. I'd really like to add it to my tool belt. I just haven't found the secret decoder ring yet. ;-) |> I've got a method returning a pointer to a C++ class instance, and |> right now I can't use it as a callable because boost::python treats it like |> a pointer. | |I don't think that's the problem. Ok. |> Traceback (most recent call last): |> ... |> File "osg_to_sgg.py", line 153, in setupGeode |> v[0].set( 0, 1, 2 ) |> Boost.Python.ArgumentError: Python argument types in |> Vec3Array.__getitem__(Vec3Array, int) | |__getitem__ refers to the square brackets operator, so this has |nothing to do with callability of the Vec3Array object. Thanks, I realized that. The boost-wrapped Vec3Array defines it's own __getitem__ method (see below). |> did not match C++ signature: |> __getitem__(osg::TemplateArray*, int) |> Note that the Vec3Array type is identical to the osg::TemplateArray<...> |> type (via typedef), so the key difference is the extra "*" in the last |> line. | |Interesting; how did you generate that __getitem__ method? Its first |parameter should be a reference to a Vec3Array, not a pointer. I'll post a complete working example soon, but here are the relevent snippets describing what the PyOSG wrappers are doing: 1) This boost::python code registers the Vec3Array pyathon type: ArrayVec3.cpp: namespace PyOSG { void init_ArrayVec3() { TemplateCompArray Vec3Array("Vec3Array"); } } where the referenced types are defined in the OpenSceneGraph (OSG) headers as: namespace osg { class Vec3f { float _v[3]; ... }; typedef Vec3f Vec3; // <------- Vec3 template class TemplateArray : public Array, public std::vector { ... } typedef TemplateArray Vec3Array; // <------- Vec3Array } 2) Here's the TemplateCompArray definition referred to in the boost::python code above: TemplateCompArray.hpp: using namespace boost::python; template class TemplateCompArray { private: class_, bases, boost::noncopyable> _array; public : TemplateCompArray(const char * name) : _array(name, boost::python::no_init) { _array .def(init<>()) ... .def("__getitem__", &getitem, return_internal_reference<>()) ... ; } static BT& getitem(T * self, int idx) { if (self->size() <= (unsigned int) idx) { PyErr_SetString(PyExc_IndexError, "assignment index out of range"); throw_error_already_set(); } return (*self)[idx]; } ... }; 3) Here is the b::p wrap for one OpenSceneGraph API which can return a ptr to a Vec3Array (actually, a pointer an Array, it's base class). This retrieved pointer causes problems when I try to call one of the Vec3Array's methods with it: Geometry.cpp: namespace PyOSG { void init_Geometry() { ... { class_, bases > geometry("Geometry", no_init); scope geometry_scope(geometry); geometry .def(init<>()) ... .def("getVertexArray", // <------------ THIS ONE (osg::Array *(osg::Geometry::*)()) &osg::Geometry::getVertexArray, return_value_policy()) ... ; ... } ... } } // namespace PyOSG Here is the actual wrapped definition of the getVertexArray() method being wrapped: Geometry: namespace osg { class Geometry : public Drawable { public: ... Array* getVertexArray(); } 4) And finally here's the definition of the "manage_osg_object" return value policy reference above in the getVertexArray() b::p wrapper: held_ptr.cpp: struct manage_osg_object { template struct apply { BOOST_STATIC_CONSTANT( bool, ok = boost::is_pointer::value || boost::is_reference::value); typedef typename boost::mpl::if_c< ok , boost::python::to_python_indirect , manage_osg_object_requires_a_pointer_or_reference_return_type >::type type; }; }; struct make_osg_holder { template static PyObject* execute(T* p) { typedef osg::ref_ptr smart_pointer; typedef boost::python::objects::pointer_holder holder_t; smart_pointer ptr(p); return boost::python::objects::make_ptr_instance::execute(ptr); } }; The puzzling thing about all this is, when I create an osg.Vec3Array inside of Python, then I can call methods (such as __getitem__, set, etc.) on that Vec3Array from inside Python with no problem. But if I obtain a reference to a Vec3Array (e.g. returned from that Geometry::getVertexArray() API above) which was generated internal to OpenSceneGraph), then I get the error message I mentioned previously. This makes me thing something isn't being correctly done inside that "manage_osg_object" return policy, but I have no clue what that is yet. Thanks, Randall From dave at boost-consulting.com Sun Nov 5 16:23:10 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 05 Nov 2006 10:23:10 -0500 Subject: [C++-sig] Type conversion problem -- simplified References: <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> <20061104152127.GA16288@charter.net> <87irhuhq61.fsf@pereiro.luannocracy.com> <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <87odrmhqd0.fsf@pereiro.luannocracy.com> <20061104231744.GA20294@charter.net> Message-ID: <87veltapep.fsf@pereiro.luannocracy.com> Randall Hopper writes: > The puzzling thing about all this is, when I create an osg.Vec3Array inside > of Python, then I can call methods (such as __getitem__, set, etc.) on that > Vec3Array from inside Python with no problem. > > But if I obtain a reference to a Vec3Array (e.g. returned from that > Geometry::getVertexArray() API above) which was generated internal to > OpenSceneGraph), then I get the error message I mentioned previously. When you pass both kinds of Python Vec3Array object to type(), do you see the same thing in both cases? > This makes me thing something isn't being correctly done inside that > "manage_osg_object" return policy, but I have no clue what that is > yet. What is the return type of get_pointer(x) where x is an osg::ref_ptr? -- Dave Abrahams Boost Consulting www.boost-consulting.com From viznut at charter.net Sun Nov 5 16:44:24 2006 From: viznut at charter.net (Randall Hopper) Date: Sun, 5 Nov 2006 09:44:24 -0600 Subject: [C++-sig] Type conversion problem -- simplified In-Reply-To: <87veltapep.fsf@pereiro.luannocracy.com> References: <20061104004130.GA11924@charter.net> <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> <20061104152127.GA16288@charter.net> <87irhuhq61.fsf@pereiro.luannocracy.com> <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <87odrmhqd0.fsf@pereiro.luannocracy.com> <20061104231744.GA20294@charter.net> <87veltapep.fsf@pereiro.luannocracy.com> Message-ID: <20061105154423.GA6362@charter.net> David Abrahams: |Randall Hopper writes: |> The puzzling thing about all this is, when I create an osg.Vec3Array inside |> of Python, then I can call methods (such as __getitem__, set, etc.) on that |> Vec3Array from inside Python with no problem. |> |> But if I obtain a reference to a Vec3Array (e.g. returned from that |> Geometry::getVertexArray() API above) which was generated internal to |> OpenSceneGraph), then I get the error message I mentioned previously. | |When you pass both kinds of Python Vec3Array object to type(), do you |see the same thing in both cases? Yes: |> This makes me thing something isn't being correctly done inside that |> "manage_osg_object" return policy, but I have no clue what that is |> yet. | |What is the return type of get_pointer(x) where x is an |osg::ref_ptr? (T *). Here's the relevent code: namespace osg { template inline T * get_pointer(osg::ref_ptr const & p) { return const_cast(p.get()); } } By the way, all efforts so far to trim down the code have been too sweeping to keep the problem. So I'm still binary searching to get even get a small test program. I wish I had some understanding of what the problem is so I could focus my efforts. Could you give me your perception of what it is? Thanks, Randall From dave at boost-consulting.com Sun Nov 5 19:59:08 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 05 Nov 2006 13:59:08 -0500 Subject: [C++-sig] Type conversion problem -- simplified References: <20061104004130.GA11924@charter.net> <7465b6170611032229t29567f22v975693dcc67df8d2@mail.gmail.com> <20061104152127.GA16288@charter.net> <87irhuhq61.fsf@pereiro.luannocracy.com> <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <87odrmhqd0.fsf@pereiro.luannocracy.com> <20061104231744.GA20294@charter.net> <87veltapep.fsf@pereiro.luannocracy.com> <20061105154423.GA6362@charter.net> Message-ID: <87y7qpbtz7.fsf@pereiro.luannocracy.com> Randall Hopper writes: > David Abrahams: > |Randall Hopper writes: > |> The puzzling thing about all this is, when I create an osg.Vec3Array inside > |> of Python, then I can call methods (such as __getitem__, set, etc.) on that > |> Vec3Array from inside Python with no problem. > |> > |> But if I obtain a reference to a Vec3Array (e.g. returned from that > |> Geometry::getVertexArray() API above) which was generated internal to > |> OpenSceneGraph), then I get the error message I mentioned previously. > | > |When you pass both kinds of Python Vec3Array object to type(), do you > |see the same thing in both cases? > > Yes: > > > > |> This makes me thing something isn't being correctly done inside that > |> "manage_osg_object" return policy, but I have no clue what that is > |> yet. > | > |What is the return type of get_pointer(x) where x is an > |osg::ref_ptr? > > (T *). Here's the relevent code: > > namespace osg { > > template inline T * get_pointer(osg::ref_ptr const & p) > { > return const_cast(p.get()); > } > > } > > > By the way, all efforts so far to trim down the code have been too sweeping > to keep the problem. So I'm still binary searching to get even get a small > test program. > > I wish I had some understanding of what the problem is so I could focus my > efforts. Could you give me your perception of what it is? >From Traceback (most recent call last): ... File "osg_to_sgg.py", line 153, in setupGeode v[0].set( 0, 1, 2 ) Boost.Python.ArgumentError: Python argument types in Vec3Array.__getitem__(Vec3Array, int) did not match C++ signature: __getitem__(osg::TemplateArray*, int) it's pretty clear that attempt to extract a osg::TemplateArray* from the v in the Python expression v[0] failed. Why it failed is a mystery. Certainly the 2nd argument matches, though, so you could reduce this to the problem of pass v to a wrapped C++ function with the signature void f(Vec3Array*) When a Python instance of a wrapped class T is converted to a T*, Boost.Python searches through the list of instance_holders (plural, to support MI) held by the Python instance for one that contains a T. See find_instance_impl in libs/python/src/object/class.cpp In your case the search is failing where it should succeed. I would expect you to have a single instance_holder in the chain that is in fact a python::objects::pointer_holder containing a ref_ptr. The only reasons I can think of for the match to fail are: a. some problem with typeid matching. b. the ref_ptr is in fact NULL. I think you could examine the execution of find_instance_impl in a debugger and learn a lot. -- Dave Abrahams Boost Consulting www.boost-consulting.com From d_zakaib at yahoo.com Mon Nov 6 02:46:06 2006 From: d_zakaib at yahoo.com (Dan) Date: Sun, 05 Nov 2006 17:46:06 -0800 Subject: [C++-sig] [Boost.python] Converting python file object to std::istream. Message-ID: I am exposing a C++ class to python that takes a reference to a std::istream object and operates on it. It looks something like this: class StreamReader { public: StreamReader(std::istream& strm); private: std::istream& strm_; } I would like to expose this class to python allowing a python client to pass in any python file type object (regular file object, StringIO object, stdin, etc.), as a C++ client would be able to pass any std::istream derived object. Now it seems to me that someone must have encountered this problem before, but I haven't seen any references as to how to make this work. Any ideas on the best way to proceed would be appreciated. thanks, Dan From seefeld at sympatico.ca Mon Nov 6 03:17:24 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sun, 05 Nov 2006 21:17:24 -0500 Subject: [C++-sig] [Boost.python] Converting python file object to std::istream. In-Reply-To: References: Message-ID: <454E9B34.3070003@sympatico.ca> Dan wrote: > I am exposing a C++ class to python that takes a reference to a > std::istream object and operates on it. It looks something like this: > > class StreamReader > { > public: > StreamReader(std::istream& strm); > > private: > std::istream& strm_; > } > > I would like to expose this class to python allowing a python client to > pass in any python file type object (regular file object, StringIO > object, stdin, etc.), as a C++ client would be able to pass any > std::istream derived object. > > Now it seems to me that someone must have encountered this problem > before, but I haven't seen any references as to how to make this work. > > Any ideas on the best way to proceed would be appreciated. It seems to me the correct way to do this is to implement the streambuf interface in terms of a boost::python::object, i.e. in which the xsputn() method is implemented as calling the python object's 'write' method. I haven't seen any such implementation yet. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From d_zakaib at yahoo.com Mon Nov 6 03:53:12 2006 From: d_zakaib at yahoo.com (Dan) Date: Sun, 05 Nov 2006 18:53:12 -0800 Subject: [C++-sig] [Boost.python] Converting python file object to std::istream. In-Reply-To: <454E9B34.3070003@sympatico.ca> References: <454E9B34.3070003@sympatico.ca> Message-ID: Yes, that's what I figured - I'll give it a shot. Though I think you meant the read method in my particular case; since I want an input stream object. thanks, Dan Stefan Seefeld wrote: > Dan wrote: >> I am exposing a C++ class to python that takes a reference to a >> std::istream object and operates on it. It looks something like this: >> >> class StreamReader >> { >> public: >> StreamReader(std::istream& strm); >> >> private: >> std::istream& strm_; >> } >> >> I would like to expose this class to python allowing a python client to >> pass in any python file type object (regular file object, StringIO >> object, stdin, etc.), as a C++ client would be able to pass any >> std::istream derived object. >> >> Now it seems to me that someone must have encountered this problem >> before, but I haven't seen any references as to how to make this work. >> >> Any ideas on the best way to proceed would be appreciated. > > It seems to me the correct way to do this is to implement the streambuf > interface in terms of a boost::python::object, i.e. in which the xsputn() > method is implemented as calling the python object's 'write' method. > > I haven't seen any such implementation yet. > > Regards, > Stefan > From viznut at charter.net Tue Nov 7 02:37:06 2006 From: viznut at charter.net (Randall Hopper) Date: Mon, 6 Nov 2006 19:37:06 -0600 Subject: [C++-sig] Type conversion problem -- simplified In-Reply-To: <87y7qpbtz7.fsf@pereiro.luannocracy.com> References: <20061104152127.GA16288@charter.net> <87irhuhq61.fsf@pereiro.luannocracy.com> <20061103153441.GA7425@charter.net> <20061103154619.GA7592@charter.net> <20061104004130.GA11924@charter.net> <87odrmhqd0.fsf@pereiro.luannocracy.com> <20061104231744.GA20294@charter.net> <87veltapep.fsf@pereiro.luannocracy.com> <20061105154423.GA6362@charter.net> <87y7qpbtz7.fsf@pereiro.luannocracy.com> Message-ID: <20061107013706.GA22779@charter.net> David Abrahams: |When a Python instance of a wrapped class T is converted to a T*, |Boost.Python searches through the list of instance_holders (plural, to |support MI) held by the Python instance for one that contains a T. |See find_instance_impl in libs/python/src/object/class.cpp | |In your case the search is failing where it should succeed. I would |expect you to have a single instance_holder in the chain that is in |fact a python::objects::pointer_holder containing a |ref_ptr. The only reasons I can think of for the match to |fail are: | | a. some problem with typeid matching. | b. the ref_ptr is in fact NULL. | |I think you could examine the execution of find_instance_impl in a |debugger and learn a lot. Soon as I get this work project squared away, I'll do that. Thanks for the insight! That's what I needed. Randall From beau.sapach at ualberta.ca Tue Nov 7 23:46:46 2006 From: beau.sapach at ualberta.ca (Beau Sapach) Date: Tue, 7 Nov 2006 15:46:46 -0700 Subject: [C++-sig] Insert instance..... again Message-ID: <000001c702be$9ad60eb0$d0822c10$@sapach@ualberta.ca> Hello everyone, I know it seems like I'm beating a dead horse here, but I'm not having much luck in understanding the "proper" way to use some of the C API functions. I want to insert an instance of one of my own objects into the python environment, here's what I've got so far. //get the main module PyObject * pMainModule = PyImport_ImportModule("__main__"); //insert MyType into the main module Py_INCREF(MyType); PyModule_AddObject(pMainModule,"MyObject",(PyObject*)&MyType); //create an instance of mytype PyObject * MyInstance = MakeMyObject(); //get the main module's dictionary PyObject * pMainDict = PyModule_GetDict(pMainModule); //insert my instance into the dictionary under the name 'testobject' PyDict_SetItemString(pMainDict,"testobject",MyInstance); //run a script that calls some function of my 'testobject' instance PyRun_SimpleString("testobject.function()\n"); My object implements only a constructor, destructor and one function of its own. The above code crashes somewhere in the python DLL but appears to be trying to access something that's un-initialized. Is there something I'm doing wrong? The above code works fine when I insert a PyObject integer created using PyInt_FromLong(). Minus of course the unnecessary PyModule_AddObject(). What's different about my object? Is there some functionality missing? Should I be implementing some of the other functions in the PyTypeObject? Any help would be appreciated! Beau -------------- next part -------------- An HTML attachment was scrubbed... URL: From jrydberg at gnu.org Wed Nov 8 13:34:55 2006 From: jrydberg at gnu.org (Johan Rydberg) Date: Wed, 08 Nov 2006 13:34:55 +0100 Subject: [C++-sig] inherit an instance, or something Message-ID: <87hcxaktg0.fsf@gnu.org> I have what might seem to be a strange situation. I have a plugin-system which loads plugins from DSO's. Each plugin presents a factory function which returns an object that implements an abstract interface (a class). The interface could look something like this: class plugin { virtual void set_parameter (const char *name, int value); ... }; The plugin class is easily wrapped using Boost.Python, and a generic factory function could be exported which loads a DSO, finds the factory function, invokes it and returns the created instance; plugin *make_plugin (const char *dso_name); The problem comes when I in python wants to inherit from a specific plugin. The simplest way is probably to do something like this; (case 1) class my_extended_plugin(plugin): def __init__(self, ...): plugin.__init__(self) self.o = make_plugin('libmy-plugin.so') self.set_parameter = self.o.set_parameter But that to me is not a clean solution. It makes it hard to inherit From my_extended_plugin. (not possible to invoke my_extended_plugin.set_parameter correctly.) What I really want is something like this; (case 2, dso_plugin inherits plugin) class my_extended_plugin(dso_plugin): def __init__(self, ...): dso_plugin.__init__(self, 'libmy-plygin.so') Where dso_plugin.__init__ would "replace" the held pointer for 'self' with the one that make_plugin('libmy-plugin.so') returns. Is it possible to do this in anyway, or must I reside to case 1? ~j -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From roman.yakovenko at gmail.com Wed Nov 8 13:52:59 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 8 Nov 2006 14:52:59 +0200 Subject: [C++-sig] inherit an instance, or something In-Reply-To: <87hcxaktg0.fsf@gnu.org> References: <87hcxaktg0.fsf@gnu.org> Message-ID: <7465b6170611080452y580137f9i86921c1496cb3a38@mail.gmail.com> On 11/8/06, Johan Rydberg wrote: > > I have what might seem to be a strange situation. I have a > plugin-system which loads plugins from DSO's. Each plugin presents a > factory function which returns an object that implements an abstract > interface (a class). The interface could look something like this: > > class plugin > { > virtual void set_parameter (const char *name, int value); > ... > }; > > The plugin class is easily wrapped using Boost.Python, and a generic > factory function could be exported which loads a DSO, finds the > factory function, invokes it and returns the created instance; > > plugin *make_plugin (const char *dso_name); > > The problem comes when I in python wants to inherit from a specific > plugin. The simplest way is probably to do something like this; > > (case 1) > > class my_extended_plugin(plugin): > def __init__(self, ...): > plugin.__init__(self) > self.o = make_plugin('libmy-plugin.so') > self.set_parameter = self.o.set_parameter > > But that to me is not a clean solution. It makes it hard to inherit > From my_extended_plugin. (not possible to invoke > my_extended_plugin.set_parameter correctly.) > > What I really want is something like this; > > (case 2, dso_plugin inherits plugin) > > class my_extended_plugin(dso_plugin): > def __init__(self, ...): > dso_plugin.__init__(self, 'libmy-plygin.so') > > Where dso_plugin.__init__ would "replace" the held pointer for 'self' > with the one that make_plugin('libmy-plugin.so') returns. > > Is it possible to do this in anyway, or must I reside to case 1? I think you can take another approach - mix between first one and the second + automatic redirection: class dso_plugin(plugin): def __init__(self, ...): plugin.__init__(self) self.__o = make_plugin('libmy-plugin.so') def __getattr__( self, name ): return getattr( self.__o, name ) Now you can derive your plug-ins from the dso_plugin. P.S. I am not sure about exact __getattr__ implementation. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From jrydberg at gnu.org Wed Nov 8 14:18:33 2006 From: jrydberg at gnu.org (Johan Rydberg) Date: Wed, 08 Nov 2006 14:18:33 +0100 Subject: [C++-sig] inherit an instance, or something References: <87hcxaktg0.fsf@gnu.org> <7465b6170611080452y580137f9i86921c1496cb3a38@mail.gmail.com> Message-ID: <87d57ykrfa.fsf@gnu.org> "Roman Yakovenko" writes: Thanks Roman! >> class my_extended_plugin(dso_plugin): >> def __init__(self, ...): >> dso_plugin.__init__(self, 'libmy-plygin.so') >> >> Where dso_plugin.__init__ would "replace" the held pointer for 'self' >> with the one that make_plugin('libmy-plugin.so') returns. >> [...] > I think you can take another approach - mix between first one and the second > + automatic redirection: > > class dso_plugin(plugin): > def __init__(self, ...): > plugin.__init__(self) > self.__o = make_plugin('libmy-plugin.so') > > def __getattr__( self, name ): > return getattr( self.__o, name ) > > Now you can derive your plug-ins from the dso_plugin. > > P.S. > I am not sure about exact __getattr__ implementation. But __getattr__ will only be invoked for fetching attributes from an instance of dso_plugin, right? Will I be able to do things like dso_plugin.set_parameter(self, ...). In other words, override a method and invoke the default implementation. ~j -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From roman.yakovenko at gmail.com Wed Nov 8 14:30:39 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 8 Nov 2006 15:30:39 +0200 Subject: [C++-sig] inherit an instance, or something In-Reply-To: <87d57ykrfa.fsf@gnu.org> References: <87hcxaktg0.fsf@gnu.org> <7465b6170611080452y580137f9i86921c1496cb3a38@mail.gmail.com> <87d57ykrfa.fsf@gnu.org> Message-ID: <7465b6170611080530y2f468c25v86fb9f5de30312ea@mail.gmail.com> On 11/8/06, Johan Rydberg wrote: > "Roman Yakovenko" writes: > > Thanks Roman! > > >> class my_extended_plugin(dso_plugin): > >> def __init__(self, ...): > >> dso_plugin.__init__(self, 'libmy-plygin.so') > >> > >> Where dso_plugin.__init__ would "replace" the held pointer for 'self' > >> with the one that make_plugin('libmy-plugin.so') returns. > >> [...] > > I think you can take another approach - mix between first one and the second > > + automatic redirection: > > > > class dso_plugin(plugin): > > def __init__(self, ...): > > plugin.__init__(self) > > self.__o = make_plugin('libmy-plugin.so') > > > > def __getattr__( self, name ): > > return getattr( self.__o, name ) > > > > Now you can derive your plug-ins from the dso_plugin. > > > > P.S. > > I am not sure about exact __getattr__ implementation. > > But __getattr__ will only be invoked for fetching attributes from an > instance of dso_plugin, right? Will I be able to do things like > dso_plugin.set_parameter(self, ...). In other words, override a method > and invoke the default implementation. Take a look on next link: http://66.102.9.104/search?q=cache:lwJDtRkG76IJ:aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52295+%22Automatic+delegation+as+an+alternative+to+inheritance%22&hl=en&ct=clnk&cd=1 -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From beau.sapach at ualberta.ca Wed Nov 8 17:21:28 2006 From: beau.sapach at ualberta.ca (Beau Sapach) Date: Wed, 8 Nov 2006 09:21:28 -0700 Subject: [C++-sig] Insert instance..... again - solved Message-ID: <000901c70351$f1ca9bd0$d55fd370$@sapach@ualberta.ca> Hello everyone, Boy I feel sheepish, but I think I've found my problem. In my PyTypeObject I had set tp_basicsize to sizeof(C++_ClassName) instead of the sizeof(Python_struct) where Python_struct is my "typedef struct { PyObject_HEAD ..." that wraps the C++ object. The code I posted below seems to work just fine now. Beau From: Beau Sapach [mailto:beau.sapach at ualberta.ca] Sent: Tuesday, November 07, 2006 3:47 PM To: 'Development of Python/C++ integration' Subject: Insert instance..... again Hello everyone, I know it seems like I'm beating a dead horse here, but I'm not having much luck in understanding the "proper" way to use some of the C API functions. I want to insert an instance of one of my own objects into the python environment, here's what I've got so far. //get the main module PyObject * pMainModule = PyImport_ImportModule("__main__"); //insert MyType into the main module Py_INCREF(MyType); PyModule_AddObject(pMainModule,"MyObject",(PyObject*)&MyType); //create an instance of mytype PyObject * MyInstance = MakeMyObject(); //get the main module's dictionary PyObject * pMainDict = PyModule_GetDict(pMainModule); //insert my instance into the dictionary under the name 'testobject' PyDict_SetItemString(pMainDict,"testobject",MyInstance); //run a script that calls some function of my 'testobject' instance PyRun_SimpleString("testobject.function()\n"); My object implements only a constructor, destructor and one function of its own. The above code crashes somewhere in the python DLL but appears to be trying to access something that's un-initialized. Is there something I'm doing wrong? The above code works fine when I insert a PyObject integer created using PyInt_FromLong(). Minus of course the unnecessary PyModule_AddObject(). What's different about my object? Is there some functionality missing? Should I be implementing some of the other functions in the PyTypeObject? Any help would be appreciated! Beau -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Wed Nov 8 22:12:10 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 8 Nov 2006 23:12:10 +0200 Subject: [C++-sig] new call policy - return_pointee_value In-Reply-To: <7465b6170611081305o422ad4ady43a5dd8a793ea415@mail.gmail.com> References: <7465b6170611081305o422ad4ady43a5dd8a793ea415@mail.gmail.com> Message-ID: <7465b6170611081312p3df3f48eq2f3f95e1401f2543@mail.gmail.com> Good evening. I am working on some library that has a lot functions, that return pointer to some fundamental type. For example: float* get_value(); float* is actually a pointer to some instance of float and not to array. AFAIK, today it is not possible to expose such function without creating small wrapper. I created new call policy - return_pointee_value, that implements next logic: if return value is NULL pointer: return None else: return object( * return value ) Usage example: namespace bpl = boost::python; def( "get_value" , &get_value , bpl::return_value_policy< bpl::return_pointee_value >() ) Source code is attached. I think, this call policy should be added to the library. Thoughts? -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- A non-text attachment was scrubbed... Name: return_pointee_value.hpp Type: text/x-c++hdr Size: 1220 bytes Desc: not available URL: From investtcartier at yahoo.com Thu Nov 9 17:22:40 2006 From: investtcartier at yahoo.com (Kevin Jones) Date: Thu, 9 Nov 2006 08:22:40 -0800 (PST) Subject: [C++-sig] Boost.Python call policies at runtime... Message-ID: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> Hi all, Given a class called Variant that can (at runtime) contain either an int or a T*. I.E. class Variant { public: int type; union { int i; T* t; }; }; How can I create a call policy that uses return_by_value when Variant is an int or manage_new_object when Variant is a T* (based on the value of "type" at runtime)? Note: I need to wrap either the int as a python object or T* as a python object and not Variant. Any help or sugestions would be most appreciated. Best regards, Kevin Jones ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com From seefeld at sympatico.ca Thu Nov 9 17:34:40 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 09 Nov 2006 11:34:40 -0500 Subject: [C++-sig] Boost.Python call policies at runtime... In-Reply-To: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> References: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> Message-ID: <455358A0.8020300@sympatico.ca> Kevin Jones wrote: > Hi all, > > Given a class called Variant that can (at runtime) > contain either an int or a T*. > > I.E. > class Variant { > public: > int type; > union { > int i; > T* t; > }; > }; What is 'T' ? > How can I create a call policy that uses > return_by_value when Variant is an int or > manage_new_object when Variant is a T* (based on the > value of "type" at runtime)? What do you want to call that returns either of the two ? > Note: I need to wrap either the int as a python object > or T* as a python object and not Variant. You have given far too little information about what you want to do (both in C++ as well as python) for anybody to be able to help. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From roman.yakovenko at gmail.com Thu Nov 9 17:39:02 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 9 Nov 2006 18:39:02 +0200 Subject: [C++-sig] Boost.Python call policies at runtime... In-Reply-To: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> References: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> Message-ID: <7465b6170611090839l70a8cbbeq560f28c61b607329@mail.gmail.com> On 11/9/06, Kevin Jones wrote: > Hi all, > > Given a class called Variant that can (at runtime) > contain either an int or a T*. > > I.E. > class Variant { > public: > int type; > union { > int i; > T* t; > }; > }; > > How can I create a call policy that uses > return_by_value when Variant is an int or > manage_new_object when Variant is a T* (based on the > value of "type" at runtime)? > > Note: I need to wrap either the int as a python object > or T* as a python object and not Variant. > > Any help or sugestions would be most appreciated. It should not be too difficult to create one. Take a look on next files: return_value_policy.hpp manage_new_object.hpp to_python_indirect.hpp Basically you should create new class struct my_policy{ struct object_maker{ PyObject* operator()( Variant const& var ){ if( var contains T* ){ return manage_new_object::apply::type()( var.t ); } else{ return object( var.i ); } } }; typedef object_maker apply; }; def( "get_x", & get_x, return_value_policy< object_maker >() ); Something like this. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From investtcartier at yahoo.com Thu Nov 9 18:23:13 2006 From: investtcartier at yahoo.com (icsa) Date: Thu, 9 Nov 2006 09:23:13 -0800 (PST) Subject: [C++-sig] Boost.Python call policies at runtime... In-Reply-To: <455358A0.8020300@sympatico.ca> References: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> <455358A0.8020300@sympatico.ca> Message-ID: <7262368.post@talk.nabble.com> Hi Stefan, My apologies for the confusion. T is a C++ class. The crux of my issue is that I need to extract variant data from a C++ object and return the data using a return policy that is based on the type (at runtime). Kevin Stefan Seefeld wrote: > > Kevin Jones wrote: >> Hi all, >> >> Given a class called Variant that can (at runtime) >> contain either an int or a T*. >> >> I.E. >> class Variant { >> public: >> int type; >> union { >> int i; >> T* t; >> }; >> }; > > What is 'T' ? > >> How can I create a call policy that uses >> return_by_value when Variant is an int or >> manage_new_object when Variant is a T* (based on the >> value of "type" at runtime)? > > What do you want to call that returns either of the two ? > >> Note: I need to wrap either the int as a python object >> or T* as a python object and not Variant. > > You have given far too little information about what you > want to do (both in C++ as well as python) for anybody to > be able to help. > > > Regards, > Stefan > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > > -- View this message in context: http://www.nabble.com/-C%2B%2B-sig--Boost.Python-call-policies-at-runtime...-tf2602653.html#a7262368 Sent from the Python - c++-sig mailing list archive at Nabble.com. From seefeld at sympatico.ca Thu Nov 9 18:55:15 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 09 Nov 2006 12:55:15 -0500 Subject: [C++-sig] Boost.Python call policies at runtime... In-Reply-To: <7262368.post@talk.nabble.com> References: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> <455358A0.8020300@sympatico.ca> <7262368.post@talk.nabble.com> Message-ID: <45536B83.9090308@sympatico.ca> icsa wrote: > Hi Stefan, > > My apologies for the confusion. T is a C++ class. The crux of my issue is > that I need to extract variant data from a C++ object and return the data > using a return policy that is based on the type (at runtime). OK. The simplest thing would be to write a wrapper function that does the conversion of the returned Variant into a boost::python::object, i.e. namespace bpl = boost::python; bpl::object your_wrapper(your_class_returning_variant &instance) { Variant v = instance.the_method(); if (v.type == 0) return bpl::object(instance.i); // make a copy of i else return bpl::object(bpl::ptr(instance.t)); // accept t directly } That's basically the same as what Roman suggests, though IMO a bit more readable. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From seefeld at sympatico.ca Thu Nov 9 18:58:43 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 09 Nov 2006 12:58:43 -0500 Subject: [C++-sig] Boost.Python call policies at runtime... In-Reply-To: <45536B83.9090308@sympatico.ca> References: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> <455358A0.8020300@sympatico.ca> <7262368.post@talk.nabble.com> <45536B83.9090308@sympatico.ca> Message-ID: <45536C53.1060806@sympatico.ca> Stefan Seefeld wrote: > namespace bpl = boost::python; > bpl::object your_wrapper(your_class_returning_variant &instance) > { > Variant v = instance.the_method(); > if (v.type == 0) return bpl::object(instance.i); // make a copy of i > else return bpl::object(bpl::ptr(instance.t)); // accept t directly Sorry, replace 'instance' by 'v' in the preceding two lines. > } Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From amohr at pixar.com Thu Nov 9 19:10:01 2006 From: amohr at pixar.com (Alex Mohr) Date: Thu, 09 Nov 2006 10:10:01 -0800 Subject: [C++-sig] Boost.Python call policies at runtime... In-Reply-To: <45536B83.9090308@sympatico.ca> References: <20061109162240.35252.qmail@web55507.mail.re4.yahoo.com> <455358A0.8020300@sympatico.ca> <7262368.post@talk.nabble.com> <45536B83.9090308@sympatico.ca> Message-ID: <45536EF9.9050409@pixar.com> > OK. The simplest thing would be to write a wrapper function that does > the conversion of the returned Variant into a boost::python::object, > i.e. > > namespace bpl = boost::python; > bpl::object your_wrapper(your_class_returning_variant &instance) > { > Variant v = instance.the_method(); > if (v.type == 0) return bpl::object(instance.i); // make a copy of i > else return bpl::object(bpl::ptr(instance.t)); // accept t directly > } > > > That's basically the same as what Roman suggests, though IMO > a bit more readable. Why not just register a custom to_python converter for Variant. That way you can just wrap functions and methods returning Variant directly. http://www.boost.org/libs/python/doc/v2/to_python_converter.html struct variant_to_python { static PyObject *convert(Variant const &v) { // make a python object for v however you want and return it... } }; Then somewhere in your module wrapping code: to_python_converter(); Alex From pyqwt at quietplease.com Fri Nov 10 03:50:05 2006 From: pyqwt at quietplease.com (Will Welch) Date: Thu, 9 Nov 2006 18:50:05 -0800 Subject: [C++-sig] pyste, abstract classes, policy inheritance Message-ID: hi, i'm using pyste on a chain of classes that derive from an abstract base. one of the member functions returns a pointer type that needs a policy declared for it. i'm noticing that i must do the set_policy for this function in each class along the inheritance chain, rather than just once for the abstract base. is there a workaround for this? i'm brand new to boost.python and pyste, unsure if this is a boost thing or a pyste-generated wrapper thing. i don't actually want to ever call that function, by the way, but using exclude() nets me errors about it being an abstract virtual function (presumably because it is left out of the wrapper class), and that causes its wrapper's m_held declaration to fail. how does one use exclude() in this situation? finally, speaking of pyste-generated wrappers and abstract classes: i've noticed that having no virtual functions in a class that derives from an abstract class, means that the needed wrapper for the derived class isnt produced by pyste. current workaround is to add a fake virtual function declaration to the derived class. is there a fix that does not involve changing the c++ source? thanks, -- will From mklists at gmail.com Fri Nov 10 08:20:00 2006 From: mklists at gmail.com (Mark Kirk) Date: Thu, 9 Nov 2006 23:20:00 -0800 Subject: [C++-sig] from_python converter problem, unable to match C++ signature Message-ID: <6a219de80611092320v7d5b89a3sacb5fd01a00ae9a7@mail.gmail.com> Hi, I have a Python-to-C++ argument conversion problem that I've been scratching my head over for a few days. I'm hoping David or another knowledgeable community member can help me. I'm using boost::python to wrap a C++ lib that I've written. It's gone well for 95% of the lib (and, yeah, boost::python is truly fantastic), but some functions and a constructor have arguments which are a pointer to an in-house C struct. Its library has a corresponding Python extension that was wrapped using the Python C Api, and an exposed function is provided for extracting the pointer to the C struct from the PyObject. Furthermore, the header for the Python extension has an extern declaration for the C struct's corresponding PyTypeObject. This Python extension makes its symbols globally available through a call to sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL). I am unable to convert function arguments from Python extension objects of the in-house data type to the corresponding C++ pointers; The extension builds (with caveats below), but I get a runtime Boost.Python.ArgumentError telling me that the args do not match the C++ signature. With me so far? I've boiled this down to a simple example which exhibits the problem. For purposes of this discussion: mytest - the example C++ lib that I'm extending via boost::python foo - C library for in-house data type FOO - the in-house C data type inhouse.foo - Python C Api extension of foo library The converter strategy I'm using is similar to boost_1_32_0/libs/python/test/m1.cpp. Here are some code snippets: mytest.h (trivial mytest.cc omitted for brevity) ------------------------------------------------ #include class mytest { public: mytest(); mytest(FOO *aFoo); ~mytest(); void f(FOO *aFoo) const; private: int mX; }; pymytest.cc (boost::python wrapper) ----------------------------------- #include #include // from Python extension for FOO #include "mytest.h" #include "foo_internal.h" // *see note1 using namespace boost::python; struct foo_from_python { static FOO*& execute(PyObject& p) { static FOO* a = FooObject_ptr(&p); return a; } }; BOOST_PYTHON_MODULE(_mytest) { lvalue_from_pytype(); class_("mytest", init<>()) .def("mytest", init()) // *see note2 .def("f", &mytest::f); } __init__.py for mytest extension -------------------------------- # need inhouse.foo's symbols loaded first import inhouse.foo from _mytest import * python/fooobject.h ------------------ // extern "C", etc. #include #include FOO* FooObject_ptr(PyObject* object); // performs a PyObject_TypeCheck() // then returns the embedded FOO* extern PyTypeObject FooObject_Type; __init__.py excerpt for foo extension ------------------------------------- # The author of this extension added some functionality in Python # and chose to inherit from the actual C extension class Foo(_foo.Foo): * note1: This file should *not* be included, but I can't build without it. It defines the FOO type. I get a number of compiler errors from boost::python::type_id() not being able to do its thing because FOO is an undefined type. * note2: The constructor causes a number of compiler errors difficult to summarize or understand beginning in def_vistor_access::visit(). I've left it commented out trying to address the other errors first. Using gcc3.4.3 on RHEL4 Linux with boost 1.32.0, Python 2.4.2. If I include the foo_internal.h header and comment out the constructor taking the FOO* argument, the extensions builds cleanly, but I still have a problem. Here's what happens in Python: Python 2.4.2 (#104, Sep 18 2006, 18:00:37) [GCC 3.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import inhouse.foo >>> from inhouse import mytest >>> fooObj = inhouse.foo.Foo() >>> mytestObj = mytest.mytest() >>> mytestObj.f(fooObj) Traceback (most recent call last): File "", line 1, in ? Boost.Python.ArgumentError : Python argument types in mytest.f(mytest, Foo) did not match C++ signature: f(mytest {lvalue}, FOO*) OK, after all that exposition, here are some questions: 1) Is lvalue_from_pytype<> the correct or best way to perform the conversion? Some other converter type? It's easy to write thin wrappers for the member functions which have FOO* args (though tedious) and doing this avoids needing to include the foo_internal.h header for the type_id() problem. However, I don't know how I would wrap the constructor. Beyond that, the FOO data type is heavily used, so a proper converter is desirable. The foo_from_python extractor class above is equivalent to: extract_member, &FooObject_Type>() However, PyFOOObject is defined in the .c file of the foo Python extension (though I might be able to convince the author to move it to the header): typedef struct { PyObject_HEAD PyObject* userArgs; FOO* foo; } PyFOOObject; 2) I verified that my converter is being registered by calling converter::registry::query(type_info(typeid(ANI*))), but it seems that it's never used. Have I mismatched a type somehow? I believe boost::python iterates through registered lvalue converters until it finds one that returns non-NULL. Correct? Again, I think my converter is never invoked. I looked into the opaque pointer converters, but it seemed like the wrong path. I can't extract the FOO* from the PyObject using them either, correct? 3) I was concerned that the inhouse.foo.Foo Python class was a problem since the "real" Python FOO type is inhouse.foo._foo.Foo. However, the PyObject_TypeCheck macro appears to properly check subtypes. Also, if I pass in an inhouse.foo._foo.Foo object, I get the same ArgumentError. And, I verified the PyObject's ob_type field is the address of FooObjectType. Despite all of this, does anyone think there might be a problem here? I'm frustrated and forced to admit I'm stuck on this one. If anyone can enlighten me or has a *solution*, I would be incredibly grateful. I feel like this must be a common task, yet I've found few relevant threads addressing converters. This leads me to wonder if I'm missing something obvious. I'm happy to provide any further info. And, if you made it through this, I appreciate your patience! thanks, mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Fri Nov 10 09:41:10 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Fri, 10 Nov 2006 10:41:10 +0200 Subject: [C++-sig] pyste, abstract classes, policy inheritance In-Reply-To: References: Message-ID: <7465b6170611100041mab39759vf59d4f51f1716625@mail.gmail.com> On 11/10/06, Will Welch wrote: > hi, > > i'm using pyste on a chain of classes that derive from an abstract > base. one of the member functions returns a pointer type that needs a > policy declared for it. i'm noticing that i must do the set_policy for > this function in each class along the inheritance chain, rather than > just once for the abstract base. is there a workaround for this? i'm > brand new to boost.python and pyste, unsure if this is a boost thing or > a pyste-generated wrapper thing. > > i don't actually want to ever call that function, by the way, but using > exclude() nets me errors about it being an abstract virtual function > (presumably because it is left out of the wrapper class), and that > causes its wrapper's m_held declaration to fail. how does one use > exclude() in this situation? > > finally, speaking of pyste-generated wrappers and abstract classes: > i've noticed that having no virtual functions in a class that derives > from an abstract class, means that the needed wrapper for the derived > class isnt produced by pyste. current workaround is to add a fake > virtual function declaration to the derived class. is there a fix that > does not involve changing the c++ source? Pyste is not under development any more. Try Py++. It is very easy to do what you are asking for with it: http://language-binding.net/pyplusplus/pyplusplus.html -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From dave at boost-consulting.com Sat Nov 11 03:02:55 2006 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 10 Nov 2006 21:02:55 -0500 Subject: [C++-sig] from_python converter problem, unable to match C++ signature References: <6a219de80611092320v7d5b89a3sacb5fd01a00ae9a7@mail.gmail.com> Message-ID: <87fycqhh9s.fsf@pereiro.luannocracy.com> "Mark Kirk" writes: > Hi, > > I have a Python-to-C++ argument conversion problem that I've been scratching > my head over for a few days. I'm hoping David or another knowledgeable > community member can help me. > > I'm using boost::python to wrap a C++ lib that I've written. It's gone well > for 95% of the lib (and, yeah, boost::python is truly fantastic), but some > functions and a constructor have arguments which are a pointer to an > in-house C struct. Its library has a corresponding Python extension that > was wrapped using the Python C Api, and an exposed function is provided for > extracting the pointer to the C struct from the PyObject. Furthermore, the > header for the Python extension has an extern declaration for the C struct's > corresponding PyTypeObject. This Python extension makes its symbols > globally available through a call to sys.setdlopenflags(dl.RTLD_NOW | > dl.RTLD_GLOBAL). That makes everybody's symbols globally available, potentially causing clashes which might be silent ODR violations causing all sorts of havoc. That said, if you control all the C++ names in the system, and use namespaces carefully, you'll probably be OK. > I am unable to convert function arguments from Python > extension objects of the in-house data type to the corresponding C++ > pointers; The extension builds (with caveats below), but I get a runtime > Boost.Python.ArgumentError telling me that the args do not match the C++ > signature. With me so far? Yes. Did you register a from-python converter for the in-house data type? > I've boiled this down to a simple example which exhibits the problem. For > purposes of this discussion: > > mytest - the example C++ lib that I'm extending via boost::python > foo - C library for in-house data type > FOO - the in-house C data type > inhouse.foo - Python C Api extension of foo library > > The converter strategy I'm using is similar to > boost_1_32_0/libs/python/test/m1.cpp. Here are some code snippets: > > mytest.h (trivial mytest.cc omitted for brevity) > ------------------------------------------------ > #include > > class mytest > { > public: > mytest(); > mytest(FOO *aFoo); > ~mytest(); > void f(FOO *aFoo) const; > private: > int mX; > }; > > pymytest.cc (boost::python wrapper) > ----------------------------------- > #include > #include // from Python extension for FOO > #include "mytest.h" > #include "foo_internal.h" // *see note1 > > using namespace boost::python; > > struct foo_from_python > { > static FOO*& execute(PyObject& p) > { > static FOO* a = FooObject_ptr(&p); ^^^^^^ hey; what's up with that? > return a; > } > }; Don't try to convert to pointers; there are no pointers in Boost.Python; only lvalues and rvalues ;-) void* extract_foo(PyObject* op) { return FooObject_ptr(op); } boost::python::converter::registry::insert( &extractor_foo, boost::python::type_id()); > > I'm frustrated and forced to admit I'm stuck on this one. If anyone > can enlighten me or has a *solution*, I would be incredibly > grateful. I feel like this must be a common task, yet I've found > few relevant threads addressing converters. This leads me to wonder > if I'm missing something obvious. I'm happy to provide any further > info. And, if you made it through this, I appreciate your patience! Well, it's my fault for never making the converter registration interface truly public and documenting it. Sorry about that. -- Dave Abrahams Boost Consulting www.boost-consulting.com From jrydberg at gnu.org Sat Nov 11 23:49:23 2006 From: jrydberg at gnu.org (Johan Rydberg) Date: Sat, 11 Nov 2006 23:49:23 +0100 Subject: [C++-sig] indexing suite and std::vector Message-ID: <87mz6xk39o.fsf@gnu.org> Hi, One of the methods I wrap return a std::vector, which needs to be wrapped as well. I was told about the indexing suite and gave it a try; class_ >("std_string_vec") .def (vector_indexing_suite > ()); With the following result; >>> repr(x) '' >>> len(x) 5 >>> x[0] Traceback (most recent call last): File "", line 1, in ? TypeError: No Python class registered for C++ class std::string I was under the impression that strings should be magically wrapped by boost.python. Any ideas anyone? ~j -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From jrydberg at gnu.org Sun Nov 12 00:07:17 2006 From: jrydberg at gnu.org (Johan Rydberg) Date: Sun, 12 Nov 2006 00:07:17 +0100 Subject: [C++-sig] indexing suite and std::vector References: <87mz6xk39o.fsf@gnu.org> Message-ID: <87ac2xk2fu.fsf@gnu.org> Johan Rydberg writes: > One of the methods I wrap return a std::vector, which > needs to be wrapped as well. I was told about the indexing suite and > gave it a try; > > class_ >("std_string_vec") > .def (vector_indexing_suite > ()); > > [...] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: No Python class registered for C++ class std::string Please ignore. If I had used my google-fu instead I would have found the answer directly. For future reference; http://mail.python.org/pipermail/c++-sig/2004-March/007025.html ~j -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 190 bytes Desc: not available URL: From kanand at qualcomm.com Sun Nov 12 06:49:32 2006 From: kanand at qualcomm.com (Anand, Kumar) Date: Sat, 11 Nov 2006 21:49:32 -0800 Subject: [C++-sig] ArgumentError: Python argument types in None.None Message-ID: I have a base class and a derived class (in say userTypes.h & userTypes.cpp) and this is built into a static library (say libuserTypes.a) ---------------------------- class Base { public: int x; Base(int i); }; class Derived : public Base { public: int y; Derived(int i, int j); }; ---------------------------- I exposed both these classes to python (using Boost Python) in a Boost_UserTypes.so module. (Note: My .so links against the static libuserTypes.a). All this works perfectly and I am able to import the module in a python script and use it. Now I built another module Boost_UserInterfaces.so which exposes a C++ interface (using the types from libuserTypes.a). Code is as follows. ---------------------------- namespace TestFrmwkEg_Wrapper { Base* createDerivedTest(int baseX, int derivedY) { return new Derived(baseX, derivedY); } } BOOST_PYTHON_MODULE (Boost_UserInterfaces) { def("createDerivedTest", &TestFrmwkEg_Wrapper::createDerivedTest, bp::return_value_policy()); } ---------------------------- Note: My function returns a base class pointer to derived class instance. Boost_UserInterfaces.so also links against the static libuserTypes.a. Now in my python script when I do the following: ---------------------------- import Boost_UserInterfaces import Boost_UserTypes dr = Boost_UserInterfaces.createDerivedTest(3, 8) print dr.y ---------------------------- I get the following error when I try to access attribute 'y' of the derived object. Boost.Python.ArgumentError: Python argument types in None.None(Derived) did not match C++ signature: None(Derived {lvalue}) -Can anyone explain to me why this is happening? I used pdb.set_trace to examine the dr variable and everything looks ok. (Pdb) dir(dr) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__instance_size__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'x', 'y'] (Pdb) print dr I understand that linking the static .a library twice (once in every .so) is a bad thing to do, but I would still like to understand the reasons for this error. If print and dir command are showing the correct derived object as expected, why is the access to the derived class attribute failing? Thanks Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From healeyjames at yahoo.co.uk Sun Nov 12 16:30:09 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Sun, 12 Nov 2006 15:30:09 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ Message-ID: <20061112153009.80180.qmail@web23106.mail.ird.yahoo.com> Can any body tell me how you create a python class from within c++? so in my .py file I have class MyClass: def f(self): return 'hello world' And from my c++ code i want to be able to do.... x = new MyClass x.f() oh and im using boost as well, if that makes it any easier. Regards. Jimmy. ___________________________________________________________ Inbox full of spam? Get leading spam protection and 1GB storage with All New Yahoo! Mail. http://uk.docs.yahoo.com/nowyoucan.html From seefeld at sympatico.ca Sun Nov 12 17:34:29 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sun, 12 Nov 2006 11:34:29 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061112153009.80180.qmail@web23106.mail.ird.yahoo.com> References: <20061112153009.80180.qmail@web23106.mail.ird.yahoo.com> Message-ID: <45574D15.1090505@sympatico.ca> James Healey wrote: > Can any body tell me how you create a python class > from within c++? > > so in my .py file I have > > class MyClass: > def f(self): > return 'hello world' > > > And from my c++ code i want to be able to do.... > > x = new MyClass > x.f() namespace bpl = boost::python; bpl::dict global; bpl::exec_file("your_file.py", global, global); // load the definition bpl::object my_class = global["MyClass"]; // extract the new type bpl::object my_instance = my_class(); // instantiate it bpl::object retn = my_instance.attr("f")(); // call it std::string value = bpl::extract(retn); // extract return value HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From mklists at gmail.com Mon Nov 13 22:44:24 2006 From: mklists at gmail.com (Mark Kirk) Date: Mon, 13 Nov 2006 13:44:24 -0800 Subject: [C++-sig] from_python converter problem, unable to match C++ signature In-Reply-To: <87fycqhh9s.fsf@pereiro.luannocracy.com> References: <6a219de80611092320v7d5b89a3sacb5fd01a00ae9a7@mail.gmail.com> <87fycqhh9s.fsf@pereiro.luannocracy.com> Message-ID: <6a219de80611131344k7ca66368te5f3d2af78a018b3@mail.gmail.com> David, Thanks for responding; I really appreciate it. You cleared up a few things for me, and your suggestions got me half-way there. The converter works now for the member function, but still no luck with the constructor. I'll explain below. I think there are some good points made here for other boost.python novices like myself, so I want to comment on a few things. Hopefully, folks in the know will correct anything I misstate. On 11/10/06, David Abrahams wrote: > > "Mark Kirk" writes: > > This Python extension makes its symbols > > globally available through a call to sys.setdlopenflags(dl.RTLD_NOW | > > dl.RTLD_GLOBAL). > > That makes everybody's symbols globally available, potentially causing > clashes which might be silent ODR violations causing all sorts of > havoc. That said, if you control all the C++ names in the system, and use > namespaces carefully, you'll probably be OK. I should have added that the dlopen flags are reset in the __init__.py after the extension is imported: flags = sys.getdlopenflags() sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL) import _foo # Reset the dlopen flags sys.setdlopenflags(flags) del flags This limits the export to just this extension's symbols unless I'm missing something. > > > struct foo_from_python > > { > > static FOO*& execute(PyObject& p) > > { > > static FOO* a = FooObject_ptr(&p); > ^^^^^^ > hey; what's up with that? > > return a; > > } > > }; Heh... yeah, that was pretty bogus, but I was hacking around the compiler being upset about initializing a reference from a temporary (even though it would have been valid after the function call ended). I thought I'd get rid of that "static" cheat later if I could make other things work. Late Friday afternoon before I saw your mail, a colleague who had been looking at this with me came up with a refinement that worked for converting FOO* in member functions (not constructors): struct foo_from_python { static FOO& execute(PyObject& p) { return *(FooObject_ptr(&p)); } }; BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(FOO); lvalue_from_pytype(); He used the BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID macro to obviate the need to include the foo_internal.h header. Don't try to convert to pointers; there are no pointers in > Boost.Python; only lvalues and rvalues ;-) > > void* extract_foo(PyObject* op) > { > return FooObject_ptr(op); > } > > boost::python::converter::registry::insert( > &extractor_foo, boost::python::type_id()); Friday night I saw your mail, which *really* cleared up a few things -- not to try converting pointers being the most important. Like a lot of programmers, I'm afraid I suffer from an incomplete understanding of lvalue and rvalue. They have a history of ambiguity. I'd considered a pointer variable to be an lvalue since you can assign to it (even though it's holding an address). Thanks for enlightening me. I needed it. With your suggested solution, I could get rid of foo_Internal.h using the opaque specialized type_id macro as above. I believe that macro simply examines the tp_name field in a PyTypeObject rather than using C++ typeid() (which is wrapped by boost::python::type_id()). Is this an acceptable way to do this since I shouldn't really use foo_internal.h? Unfortunately, I'm still unable to get the constructor to work. I get compiler errors from boost.python, but, after looking through the boost.python source, I'm still stumped. My metaprogramming fu is just not there. I'm reluctant to post the complete errors here (but I'm happy if someone is up for it), so here's an abbreviated version of the chain of five errors: --------------------- sys_include/boost/python/def_visitor.hpp: In static member function `static void boost::python::def_visitor_access::visit(const V&, classT&, const char*, const OptionalArgs&) [with V = boost::python::def_visitor::visit(classT&, const char*, const OptionalArgs&) const [with classT = boost::python::class_, OptionalArgs = boost::python::detail::def_helper::def_impl(T*, const char*, LeafVisitor, const Helper&, const boost::python::def_visitor*) [with T = bpani, Helper = boost::python::detail::def_helper, LeafVisitor = boost::python::init& boost::python::class_::def(const char*, F) [with F = boost::python::init, W = bpani, X1 = boost::python::detail::not_specified, X2 = boost::python::detail::not_specified, X3 = boost::python::detail::not_specified]' lib/bpfoo/python/pybpfoo.cc:39: instantiated from here sys_include/boost/python/def_visitor.hpp:43: error: no matching function for call to `boost::python::init interface truly public and documenting it. Sorry about that. Ha! Well, yeah, that would have made things easier I suppose, but I'm just grateful for having boost.python at all. It's made wrapping C++ libs extremely efficient. Unfortunately, this particular problem has become a show-stopper for me. Many of my colleagues will likely need to do this eventually, so we must solve it somehow or come up with another way to wrap many of our libs (which would be a drag). thanks, mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From mharidev at qualcomm.com Tue Nov 14 01:56:54 2006 From: mharidev at qualcomm.com (Haridev, Meghana) Date: Mon, 13 Nov 2006 16:56:54 -0800 Subject: [C++-sig] Using PYPP_API Message-ID: <5383A81D5EB8F14FBDB487D9B5FBEA8801D57915@NAEX11.na.qualcomm.com> Hi Folks, I'm using Py++ for the generation of boost.python wrappers. I would like to use a high level API which is built on top of Py++ to abstract away the internal details of Py++/pygccxml. What is the status of the development of the PYPP_API? Is it stable enough to be used to generate consistent/reliable code in terms of using Py++ under the hood? Are all features of Py++ supported by the API or exposed in a manner that users can still use raw Py++ if need be? Thanks! -Meghana. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Tue Nov 14 07:11:15 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 14 Nov 2006 08:11:15 +0200 Subject: [C++-sig] Using PYPP_API In-Reply-To: <5383A81D5EB8F14FBDB487D9B5FBEA8801D57915@NAEX11.na.qualcomm.com> References: <5383A81D5EB8F14FBDB487D9B5FBEA8801D57915@NAEX11.na.qualcomm.com> Message-ID: <7465b6170611132211r13cd9cb7rbf74b14a55cbcf3e@mail.gmail.com> On 11/14/06, Haridev, Meghana wrote: > Hi Folks, > I'm using Py++ for the generation of boost.python wrappers. > I would like to use a high level API which is built on top of Py++ to > abstract away the internal details of Py++/pygccxml. What do you consider as internal details of Py++/pygccxml and what interface do you prefer to see ? -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From noah.schwartz1 at gmail.com Tue Nov 14 18:17:46 2006 From: noah.schwartz1 at gmail.com (Noah Schwartz) Date: Tue, 14 Nov 2006 12:17:46 -0500 Subject: [C++-sig] __str__ method for wrapper classes Message-ID: <200611141217.46693.noah.schwartz1@gmail.com> Hi, I have an inheritance scheme in my C++ library. I expose the base class to python using the method described in the tutorial (a struct that inherits from my class and from wrapper). I have the extraction operator implemented for the base class (lets call the base class MyClass). I want to be able to print MyClass as a string in python. I added .def(str(self)) to the class object for the wrapper (MyClassWrap) thinking it would work but, python complains that the __str__ method did not match the C++ signature: Boost.Python.ArgumentError: Python argument types in MyClass.__str__(MyClass) did not match C++ signature: __str__(MyClassWrap {lvalue}) I think the problem is that I defined the __str__ method for MyClassWrap and not for MyClass. Since MyClassWrap also inherits from wrapper, it can't use MyClass's extraction operator. I don't have a class_ object for MyClass. I only have it for MyClassWrap and the other classes that inherit from MyClass. How do I fix this? Noag From amohr at pixar.com Tue Nov 14 18:38:13 2006 From: amohr at pixar.com (Alex Mohr) Date: Tue, 14 Nov 2006 09:38:13 -0800 Subject: [C++-sig] __str__ method for wrapper classes In-Reply-To: <200611141217.46693.noah.schwartz1@gmail.com> References: <200611141217.46693.noah.schwartz1@gmail.com> Message-ID: <4559FF05.4060106@pixar.com> > I want to be able to print MyClass as a string in python. I > added .def(str(self)) to the class object for the wrapper (MyClassWrap) > thinking it would work but, python complains that the __str__ method did not > match the C++ signature: > > Boost.Python.ArgumentError: Python argument types in > MyClass.__str__(MyClass) > did not match C++ signature: > __str__(MyClassWrap {lvalue}) > > I think the problem is that I defined the __str__ method for MyClassWrap and > not for MyClass. Since MyClassWrap also inherits from wrapper, it can't use > MyClass's extraction operator. I don't have a class_ object for MyClass. I > only have it for MyClassWrap and the other classes that inherit from MyClass. > How do I fix this? From a cursory inspection, I believe this is the same bug as that mentioned in this thread: http://mail.python.org/pipermail/c++-sig/2006-September/011336.html which David has already fixed in CVS. Unfortunately, I don't know when the next version of boost (and boost python) will be out, so I can't say when you'll get it. As a workaround, I think you can do something like this in your wrapping code: class<...>(...) .def("__str__", boost::lexical_cast) if MyClass is streamable. If it's not, you can always do something totally custom: static std::string MyClass__str__(MyClass const &self) { return std::string("Whatever I want."); } class<...>(...) .def("__str__", MyClass__str__) Alex From noah.schwartz1 at gmail.com Tue Nov 14 21:08:33 2006 From: noah.schwartz1 at gmail.com (Noah Schwartz) Date: Tue, 14 Nov 2006 15:08:33 -0500 Subject: [C++-sig] __str__ method for wrapper classes In-Reply-To: <4559FF05.4060106@pixar.com> References: <200611141217.46693.noah.schwartz1@gmail.com> <4559FF05.4060106@pixar.com> Message-ID: <200611141508.33943.noah.schwartz1@gmail.com> On Tuesday 14 November 2006 12:38, Alex Mohr wrote: > From a cursory inspection, I believe this is the same bug as that > mentioned in this thread: > > http://mail.python.org/pipermail/c++-sig/2006-September/011336.html > > which David has already fixed in CVS. Unfortunately, I don't know when > the next version of boost (and boost python) will be out, so I can't say > when you'll get it. > > As a workaround, I think you can do something like this in your wrapping > code: > > class<...>(...) > .def("__str__", boost::lexical_cast) > > if MyClass is streamable. If it's not, you can always do something > totally custom: > > static std::string MyClass__str__(MyClass const &self) { > return std::string("Whatever I want."); > } > > class<...>(...) > .def("__str__", MyClass__str__) > Used the second one. It works nicely. Thanks. > Alex > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig From johan2sson at gmail.com Wed Nov 15 00:26:06 2006 From: johan2sson at gmail.com (Johan Johansson) Date: Wed, 15 Nov 2006 00:26:06 +0100 Subject: [C++-sig] vector -> list Message-ID: Dear list, What would be the best way to return a rather largish vector of integers to Python from a C++ function? And while I'm at it, what would be the best way of iterating through a boost::python::list? Obviously two very basic questions, but neither google nor grep seems to know the answers. Thanks in advance, Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Wed Nov 15 02:26:01 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 14 Nov 2006 20:26:01 -0500 Subject: [C++-sig] vector -> list In-Reply-To: References: Message-ID: <455A6CA9.4050607@sympatico.ca> Johan Johansson wrote: > Dear list, > > What would be the best way to return a rather largish vector of integers > to Python from a C++ function? And while I'm at it, what would be the > best way of iterating through a boost::python::list? You may want to look at http://boost.org/libs/python/doc/v2/indexing.html for the first. For the second, I believe the 'for a in [...]' style gives as good a performance as you can get. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From healeyjames at yahoo.co.uk Wed Nov 15 13:36:13 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Wed, 15 Nov 2006 12:36:13 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: Message-ID: <20061115123614.85925.qmail@web23112.mail.ird.yahoo.com> > James Healey wrote: > > Can any body tell me how you create a python class > > from within c++? > > > > so in my .py file I have > > > > class MyClass: > > def f(self): > > return 'hello world' > > > > > > And from my c++ code i want to be able to do.... > > > > x = new MyClass > > x.f() > > namespace bpl = boost::python; > bpl::dict global; > bpl::exec_file("your_file.py", global, global); > // load the definition > bpl::object my_class = global["MyClass"]; > // extract the new type > bpl::object my_instance = my_class(); > // instantiate it > bpl::object retn = my_instance.attr("f")(); > // call it > std::string value = bpl::extract(retn); > // extract return value > > HTH, > Stefan I dont seem to have the exec_file command in my current boost build, I'm using 1.33.1 which was downloaded via the boost website. Send instant messages to your online friends http://uk.messenger.yahoo.com From seefeld at sympatico.ca Wed Nov 15 14:39:33 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 08:39:33 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061115123614.85925.qmail@web23112.mail.ird.yahoo.com> References: <20061115123614.85925.qmail@web23112.mail.ird.yahoo.com> Message-ID: <455B1895.7010000@sympatico.ca> James Healey wrote: >> James Healey wrote: >>> Can any body tell me how you create a python class >>> from within c++? >>> >>> so in my .py file I have >>> >>> class MyClass: >>> def f(self): >>> return 'hello world' >>> >>> >>> And from my c++ code i want to be able to do.... >>> >>> x = new MyClass >>> x.f() >> namespace bpl = boost::python; >> bpl::dict global; >> bpl::exec_file("your_file.py", global, global); >> // load the definition >> bpl::object my_class = global["MyClass"]; >> // extract the new type >> bpl::object my_instance = my_class(); >> // instantiate it >> bpl::object retn = my_instance.attr("f")(); >> // call it >> std::string value = bpl::extract(retn); >> // extract return value >> >> HTH, >> Stefan > > I dont seem to have the exec_file command in my > current boost build, I'm using 1.33.1 which was > downloaded via the boost website. True, it has been added to boost.python sometime 2005, but unfortunately didn't make it into the 1.33 release. If you can't wait a current snapshot, you can take a verbatim copy of the function: // Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract(filename); // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, "r"); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); PyObject* result = PyRun_File(PyFile_AsFile(file.get()), f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); } HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From healeyjames at yahoo.co.uk Wed Nov 15 16:30:53 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Wed, 15 Nov 2006 15:30:53 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B1895.7010000@sympatico.ca> Message-ID: <20061115153053.88667.qmail@web23102.mail.ird.yahoo.com> > > True, it has been added to boost.python sometime > 2005, > but unfortunately didn't make it into the 1.33 > release. > > If you can't wait a current snapshot, you can take a > verbatim copy of the function: > > // Execute python source code from file filename. > // global and local are the global and local scopes > respectively, > // used during execution. > object BOOST_PYTHON_DECL exec_file(str filename, > object global, object local) > { > // should be 'char const *' but older python > versions don't use 'const' yet. > char *f = python::extract(filename); > // Let python open the file to avoid potential > binary incompatibilities. > PyObject *pyfile = PyFile_FromString(f, "r"); > if (!pyfile) throw > std::invalid_argument(std::string(f) + " : no such > file"); > python::handle<> file(pyfile); > PyObject* result = > PyRun_File(PyFile_AsFile(file.get()), > f, > Py_file_input, > global.ptr(), local.ptr()); > if (!result) throw_error_already_set(); > return object(detail::new_reference(result)); > } > > HTH, > Stefan When I run the PyRun_File command result comes back as NULL. The only thing im doing before calling exec_file is Py_Initialize(); Regards. Jimmy. Send instant messages to your online friends http://uk.messenger.yahoo.com From seefeld at sympatico.ca Wed Nov 15 17:09:18 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 11:09:18 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061115153053.88667.qmail@web23102.mail.ird.yahoo.com> References: <20061115153053.88667.qmail@web23102.mail.ird.yahoo.com> Message-ID: <455B3BAE.9070100@sympatico.ca> James Healey wrote: > When I run the PyRun_File command result comes back as > NULL. The only thing im doing before calling exec_file > is Py_Initialize(); Check the exception python has set. It should tell you why the execution failed. (Does the file actually exist ? Can it be executed by python without error ?) boost.python should actually translate that exception into a C++ exception, which you can catch inside your C++ code... HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From healeyjames at yahoo.co.uk Wed Nov 15 19:16:55 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Wed, 15 Nov 2006 18:16:55 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B3BAE.9070100@sympatico.ca> Message-ID: <20061115181655.53688.qmail@web23111.mail.ird.yahoo.com> PyFile_AsFile returns a ptr to a file object so that's working as it should. And how do i check the exception? Do i need to do any thing with the dict that gets passed into exec_file? Regards. Jimmy. --- Stefan Seefeld wrote: > James Healey wrote: > > > When I run the PyRun_File command result comes > back as > > NULL. The only thing im doing before calling > exec_file > > is Py_Initialize(); > > Check the exception python has set. It should tell > you > why the execution failed. (Does the file actually > exist ? Can it be executed by python without error > ?) > > boost.python should actually translate that > exception into > a C++ exception, which you can catch inside your C++ > code... > > HTH, > Stefan > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > Send instant messages to your online friends http://uk.messenger.yahoo.com From seefeld at sympatico.ca Wed Nov 15 19:33:55 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 13:33:55 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061115181655.53688.qmail@web23111.mail.ird.yahoo.com> References: <20061115181655.53688.qmail@web23111.mail.ird.yahoo.com> Message-ID: <455B5D93.5090700@sympatico.ca> James Healey wrote: > PyFile_AsFile returns a ptr to a file object so that's > working as it should. > > And how do i check the exception? > > Do i need to do any thing with the dict that gets > passed into exec_file? No. If the PyFile_AsFile call returns NULL you know something is wrong, and an exception is set (i.e. PyErr_Occured() returns a non-null pointer to the exception object. However, all that should be dealt with by boost.python already. Don't you see a C++ exception fly by ? FWIW, you may want to look at the exec.cpp unit test in a boost CVS snapshot. It should test all of the above. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From seefeld at sympatico.ca Wed Nov 15 19:42:21 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 13:42:21 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B5D93.5090700@sympatico.ca> References: <20061115181655.53688.qmail@web23111.mail.ird.yahoo.com> <455B5D93.5090700@sympatico.ca> Message-ID: <455B5F8D.1020107@sympatico.ca> Stefan Seefeld wrote: > James Healey wrote: >> PyFile_AsFile returns a ptr to a file object so that's >> working as it should. >> >> And how do i check the exception? >> >> Do i need to do any thing with the dict that gets >> passed into exec_file? > > No. If the PyFile_AsFile call returns NULL you know > something is wrong, and an exception is set (i.e. I meant PyRun_File here. Sorry for the confusion. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From apocalypznow at gmail.com Wed Nov 15 20:37:56 2006 From: apocalypznow at gmail.com (apocalypznow) Date: Wed, 15 Nov 2006 11:37:56 -0800 Subject: [C++-sig] pyCXX example of a callback Message-ID: Hi, Can anyone post a simple pyCXX example of a callback into python? My python function should allow a string passed as a parameter, and returns a string, ie: def somepythonCB(s_in): s_out = dosomethingtoinputstringandreturnoutputstring(s_in) return s_out Much appreciated, thanks. From healeyjames at yahoo.co.uk Wed Nov 15 20:45:30 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Wed, 15 Nov 2006 19:45:30 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B5D93.5090700@sympatico.ca> Message-ID: <20061115194530.75819.qmail@web23106.mail.ird.yahoo.com> It seem to have some thing to do with what's in the .py file im loading, if i have it empty or do some thing simple like var = 1, then it loads fine. I did have: import MyTest MyTest() and call a test function, my c++ code looks like: BOOST_PYTHON_MODULE( MyTest ) { boost::python::def( "TestFunc", &TestFunc ); } And just before I call the exec_file function i have this... Py_Initialize(); initMyTest(); --- Stefan Seefeld wrote: > James Healey wrote: > > PyFile_AsFile returns a ptr to a file object so > that's > > working as it should. > > > > And how do i check the exception? > > > > Do i need to do any thing with the dict that gets > > passed into exec_file? > > No. If the PyFile_AsFile call returns NULL you know > something is wrong, and an exception is set (i.e. > PyErr_Occured() returns a non-null pointer to the > exception object. > > However, all that should be dealt with by > boost.python > already. Don't you see a C++ exception fly by ? > > FWIW, you may want to look at the exec.cpp unit test > in a boost CVS snapshot. It should test all of the > above. > > HTH, > Stefan > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > Send instant messages to your online friends http://uk.messenger.yahoo.com From healeyjames at yahoo.co.uk Wed Nov 15 20:49:12 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Wed, 15 Nov 2006 19:49:12 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B3BAE.9070100@sympatico.ca> Message-ID: <20061115194912.76660.qmail@web23106.mail.ird.yahoo.com> And it looks like this is the exception: exception: boost::python::error_already_set --- Stefan Seefeld wrote: > James Healey wrote: > > > When I run the PyRun_File command result comes > back as > > NULL. The only thing im doing before calling > exec_file > > is Py_Initialize(); > > Check the exception python has set. It should tell > you > why the execution failed. (Does the file actually > exist ? Can it be executed by python without error > ?) > > boost.python should actually translate that > exception into > a C++ exception, which you can catch inside your C++ > code... > > HTH, > Stefan > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > Send instant messages to your online friends http://uk.messenger.yahoo.com From seefeld at sympatico.ca Wed Nov 15 20:54:19 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 14:54:19 -0500 Subject: [C++-sig] pyCXX example of a callback In-Reply-To: References: Message-ID: <455B706B.8020504@sympatico.ca> apocalypznow wrote: > Hi, > > Can anyone post a simple pyCXX example of a callback into python? My I don't know what 'pyCXX' is, so let's assume you mean boost.python. > python function should allow a string passed as a parameter, and returns > a string, ie: > > def somepythonCB(s_in): > s_out = dosomethingtoinputstringandreturnoutputstring(s_in) > return s_out The answer is very similar to one I gave in a previous question: namespace bpl = boost::python; bpl::dict global; bpl::exec_file("your_file.py", global, global); // load the definition bpl::object func = global["somepythonCP"]; // extract python function bpl::object retn = func(input); // call it with input string std::string value = bpl::extract(retn); // extract return value The magic here is that boost.python already has builtin support for conversion between std::string and python's str. Please note that the 'exec_file' function is only in CVS, not in the last official release. See my previous posts for more on that. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From apocalypznow at gmail.com Wed Nov 15 20:59:41 2006 From: apocalypznow at gmail.com (apocalypznow) Date: Wed, 15 Nov 2006 11:59:41 -0800 Subject: [C++-sig] pyCXX example of a callback In-Reply-To: <455B706B.8020504@sympatico.ca> References: <455B706B.8020504@sympatico.ca> Message-ID: I gave up on Boost. Never could get it to build no matter what I did. Thanks anyway, but I'm looking for a pyCXX solution. Stefan Seefeld wrote: > apocalypznow wrote: > >>Hi, >> >>Can anyone post a simple pyCXX example of a callback into python? My > > > I don't know what 'pyCXX' is, so let's assume you mean boost.python. > > >>python function should allow a string passed as a parameter, and returns >>a string, ie: >> >>def somepythonCB(s_in): >> s_out = dosomethingtoinputstringandreturnoutputstring(s_in) >> return s_out > > > The answer is very similar to one I gave in a previous question: > > namespace bpl = boost::python; > bpl::dict global; > bpl::exec_file("your_file.py", global, global); // load the definition > bpl::object func = global["somepythonCP"]; // extract python function > bpl::object retn = func(input); // call it with input string > std::string value = bpl::extract(retn); // extract return value > > The magic here is that boost.python already has builtin support for > conversion between std::string and python's str. > Please note that the 'exec_file' function is only in CVS, not in the last > official release. See my previous posts for more on that. > > HTH, > Stefan > From seefeld at sympatico.ca Wed Nov 15 21:01:55 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 15:01:55 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061115194912.76660.qmail@web23106.mail.ird.yahoo.com> References: <20061115194912.76660.qmail@web23106.mail.ird.yahoo.com> Message-ID: <455B7233.2030006@sympatico.ca> James Healey wrote: > And it looks like this is the exception: > > exception: boost::python::error_already_set http://boost.org/libs/python/doc/tutorial/doc/html/python/embedding.html#python.using_the_interpreter talks a bit about catching exceptions thrown by the python runtime. Look for the section on 'Exception handling'. (The python-exception handling, such as extracting the stack trace, could probably be wrapped into a C++ API, but AFAIK it currently isn't.) HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From seefeld at sympatico.ca Wed Nov 15 21:03:07 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 15:03:07 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061115194530.75819.qmail@web23106.mail.ird.yahoo.com> References: <20061115194530.75819.qmail@web23106.mail.ird.yahoo.com> Message-ID: <455B727B.6090804@sympatico.ca> James Healey wrote: > I did have: > > import MyTest > > MyTest() This doesn't look correct. You import a module, which can't have a call operator defined. Only objects can. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From ndbecker2 at gmail.com Wed Nov 15 21:07:22 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 15 Nov 2006 15:07:22 -0500 Subject: [C++-sig] boost::python + epydoc Message-ID: I'm using epydoc-3.0alpha3. I know we've talked about this before, but I don't think the issue was resolved. When using epydoc with boost::python doc strings, you have to turn off signatures: docstring_options doc_options (true, false); Otherwise, it seems epydoc is confused. Is there any resolution to this issue? I'd rather not have to turn off the signatures to add my documentation. From seefeld at sympatico.ca Wed Nov 15 21:32:22 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 15 Nov 2006 15:32:22 -0500 Subject: [C++-sig] boost::python + epydoc In-Reply-To: References: Message-ID: <455B7956.1000307@sympatico.ca> Neal Becker wrote: > I'm using epydoc-3.0alpha3. I know we've talked about this before, but I > don't think the issue was resolved. > > When using epydoc with boost::python doc strings, you have to turn off > signatures: > > docstring_options doc_options (true, false); > > Otherwise, it seems epydoc is confused. > > Is there any resolution to this issue? I'd rather not have to turn off the > signatures to add my documentation. What is the issue with epydoc ? Do other documentation tools (happydoc, say) work fine ? (I know epydoc supports both, parsing as well as introspection to extract documentation. Is that related ?) Thanks, Stefan -- ...ich hab' noch einen Koffer in Berlin... From healeyjames at yahoo.co.uk Wed Nov 15 22:22:51 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Wed, 15 Nov 2006 21:22:51 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B727B.6090804@sympatico.ca> Message-ID: <20061115212252.71495.qmail@web23103.mail.ird.yahoo.com> Ok got the exception catch working and printing out the error and stack trace. ImportError: __import__ not found Is the error that I am getting. --- Stefan Seefeld wrote: > James Healey wrote: > > > I did have: > > > > import MyTest > > > > MyTest() > > This doesn't look correct. You import a module, > which can't have a call operator defined. Only > objects can. > > Regards, > Stefan > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > ___________________________________________________________ The all-new Yahoo! Mail goes wherever you go - free your email address from your Internet provider. http://uk.docs.yahoo.com/nowyoucan.html From roman.yakovenko at gmail.com Thu Nov 16 07:29:13 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 16 Nov 2006 08:29:13 +0200 Subject: [C++-sig] pyCXX example of a callback In-Reply-To: References: <455B706B.8020504@sympatico.ca> Message-ID: <7465b6170611152229o2af521ax74703b0fe4667512@mail.gmail.com> On 11/15/06, apocalypznow wrote: > I gave up on Boost. Never could get it to build no matter what I did. > Thanks anyway, but I'm looking for a pyCXX solution. May be you are doing this to early. Next link http://www.boost-consulting.com/download.html contains pre-build binaries for windows platform. Actually it contains nice setup. Almost any Linux distribution comes today with boost libraries. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From newsuser at stacom-software.de Thu Nov 16 08:57:17 2006 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Thu, 16 Nov 2006 08:57:17 +0100 Subject: [C++-sig] Heap cleanup in python extension Message-ID: Hello Together, hope it's ok to post a bit beside c++. Shortly what I'm doing: - Extending python with boost.pthon extension - Using python C-Api for datatypes in the extension - extension has a thread (that can be stopped/started) - thread started: extension updates a dict (given as parameter to the extension) every 20 ms - the dict looks like: {int:{int:[float,float,float] int:[float,float,float], ...}} Now my question: I create the dict every 20 ms on the heap in the following way: ------------------------------ static PyObject* createPTDict() { static int aNumIter = 0; PyObject* nRetDictPy = PyDict_New(); // dicto to return PyObject* nToolIdPy = PyInt_FromLong(1234567); PyObject* nLedDict = PyDict_New(); // dict containing 5 key,values for (int aLedNum=0; aLedNum < 5; aLedNum++) { PyObject* aLedNumPy = PyInt_FromLong(aLedNum); PyObject* aLedList = PyList_New(0); for ( int aXYZ=0; aXYZ < 3; aXYZ++) { PyObject* aLedPosXYZ = PyFloat_FromDouble(1.0); PyList_Append(aLedList, aLedPosXYZ); } PyDict_SetItem(nLedDict, aLedNumPy, aLedList); } PyDict_SetItem(nRetDictPy, nToolIdPy, nLedDict); aNumIter ++; return nRetDictPy; } ------------------------------ I give it to python with: ------------------------------ PyObject *aKey, *aValue; int aPos = 0; PyObject* aNewToolDict = createPTDict(); PyDict_Next(aNewToolDict, &aPos, &aKey, &aValue); // DictInPython passed prior to extension PyDict_SetItem(, aKey, aValue); ------------------------------ And now, what would be a proper way to cleanup the heap? 1) Does PyDict_Clear(aNewToolDict) also decrement the ref counting for the containing list, int, ... PyObjects? 2) Do I need to Py_CLEAR( PyObject *o) for every created PyObject? Thanks a lot for every answer/hint. Regards Alexander From healeyjames at yahoo.co.uk Thu Nov 16 12:44:51 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Thu, 16 Nov 2006 11:44:51 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B7233.2030006@sympatico.ca> Message-ID: <20061116114451.20994.qmail@web23102.mail.ird.yahoo.com> Ok got the exception catch working and printing out the error and stack trace. ImportError: __import__ not found Is the error that I am getting. --- Stefan Seefeld wrote: > James Healey wrote: > > And it looks like this is the exception: > > > > exception: boost::python::error_already_set > > http://boost.org/libs/python/doc/tutorial/doc/html/python/embedding.html#python.using_the_interpreter > > talks a bit about catching exceptions thrown by > the python runtime. Look for the section on > 'Exception handling'. > > (The python-exception handling, such as extracting > the stack trace, > could probably be wrapped into a C++ API, but AFAIK > it currently isn't.) > > > HTH, > Stefan > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > Send instant messages to your online friends http://uk.messenger.yahoo.com From ndbecker2 at gmail.com Thu Nov 16 13:59:23 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 16 Nov 2006 07:59:23 -0500 Subject: [C++-sig] boost::python + epydoc References: <455B7956.1000307@sympatico.ca> Message-ID: Stefan Seefeld wrote: > Neal Becker wrote: >> I'm using epydoc-3.0alpha3. I know we've talked about this before, but I >> don't think the issue was resolved. >> >> When using epydoc with boost::python doc strings, you have to turn off >> signatures: >> >> docstring_options doc_options (true, false); >> >> Otherwise, it seems epydoc is confused. >> >> Is there any resolution to this issue? I'd rather not have to turn off >> the signatures to add my documentation. > > What is the issue with epydoc ? Do other documentation tools (happydoc, > say) work fine ? (I know epydoc supports both, parsing as well as > introspection to extract documentation. Is that related ?) > > Thanks, > Stefan > I have not had time to analyze the problem. The symptoms are that this code, for example: def ("corr", &corr,ublas::vector,ublas::vector >, default_call_policies(), ( arg ("in"), arg ("coef"), arg ("size"), arg ("stride")=1 ), "correlate an input against reference coeff.\n" "@param in: input.\n" "@type in: vector_Complex\n" "@param coef: reference pattern\n" "@type coef: vector_Complex\n" "@param size: size of the output desired\n" "@type size: int\n" "@param stride: stride for input (def=1)\n" "@type stride: int\n" ); When docstring_options is not used, epydoc doesn't pick up @param, @type, and simply renders these literally into the docstring, but when sig is turned off, these are picked up and interpreted correctly by epydoc. From seefeld at sympatico.ca Thu Nov 16 14:45:42 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 16 Nov 2006 08:45:42 -0500 Subject: [C++-sig] boost::python + epydoc In-Reply-To: References: <455B7956.1000307@sympatico.ca> Message-ID: <455C6B86.7020508@sympatico.ca> Neal, can you try to generate a minimal test case please ? I'v just tried this tiny module: --------------------- #include namespace bpl = boost::python; void function() {} BOOST_PYTHON_MODULE(bpl_epydoc) { bpl::def ("function", function, "correlate an input against reference coeff.\n" "@param in: input.\n" "@type in: vector_Complex\n" "@param coef: reference pattern\n" "@type coef: vector_Complex\n" "@param size: size of the output desired\n" "@type size: int\n" "@param stride: stride for input (def=1)\n" "@type stride: int\n" ); } --------------------- and 'epydoc bpl_epydoc.so' works just fine (with epydoc 3.0a2). Am I missing something ? Thanks, Stefan -- ...ich hab' noch einen Koffer in Berlin... From baas at ira.uka.de Thu Nov 16 14:58:07 2006 From: baas at ira.uka.de (Matthias Baas) Date: Thu, 16 Nov 2006 14:58:07 +0100 Subject: [C++-sig] Using PYPP_API In-Reply-To: <5383A81D5EB8F14FBDB487D9B5FBEA8801D57915@NAEX11.na.qualcomm.com> References: <5383A81D5EB8F14FBDB487D9B5FBEA8801D57915@NAEX11.na.qualcomm.com> Message-ID: Haridev, Meghana wrote: > I would like to use a high level API which is built on top of Py++ to > abstract away the internal details of Py++/pygccxml. > > What is the status of the development of the PYPP_API? As far as I can tell I am the only one using (and maintaining) it. I'm using it for a project of mine which still relies on pypp_api, even though Py++ meanwhile has an API that partially resembles pypp_api. > Is it stable enough to be used to generate consistent/reliable code in > terms of using Py++ under the hood? Well, at least it works for me. :) But of course, I'm only focusing on features that I need for my project, so I can't say if pypp_api is suitable for your projects as well. > Are all features of Py++ supported > by the API or exposed in a manner that users can still use raw Py++ if > need be? Usually you can mix pypp_api calls and "raw" Py++ calls unless you depend on functionality implemented in Py++' module_builder_t class. - Matthias - From ndbecker2 at gmail.com Thu Nov 16 15:07:56 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 16 Nov 2006 09:07:56 -0500 Subject: [C++-sig] boost::python + epydoc References: <455B7956.1000307@sympatico.ca> <455C6B86.7020508@sympatico.ca> Message-ID: Stefan Seefeld wrote: [...] Strange, this doesn't work here. I tried exactly the same example (except I named the module test). It says: PYTHONPATH=../blue.x86_64 epydoc -v test1 [........................... +------------------------------------------------------------------------------------------------- | File ??, in test1.function | Warning: Improper paragraph indentation. | [.....................................................................................................] The resulting html is: -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Thu Nov 16 15:20:20 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 16 Nov 2006 09:20:20 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061116114451.20994.qmail@web23102.mail.ird.yahoo.com> References: <20061116114451.20994.qmail@web23102.mail.ird.yahoo.com> Message-ID: <455C73A4.2000903@sympatico.ca> James Healey wrote: > Ok got the exception catch working and printing out > the error and stack trace. > > ImportError: __import__ not found > > Is the error that I am getting. Hmm, that's strange. It looks as if the python runtime is missing some essential piece of initialization. Unfortunately I have no idea what that could be. Sorry. Stefan -- ...ich hab' noch einen Koffer in Berlin... From seefeld at sympatico.ca Thu Nov 16 15:28:28 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 16 Nov 2006 09:28:28 -0500 Subject: [C++-sig] boost::python + epydoc In-Reply-To: References: <455B7956.1000307@sympatico.ca> <455C6B86.7020508@sympatico.ca> Message-ID: <455C758C.3070202@sympatico.ca> Neal Becker wrote: > Stefan Seefeld wrote: > > [...] > > Strange, this doesn't work here. I tried exactly the same example (except I named the module test). > It says: > PYTHONPATH=../blue.x86_64 epydoc -v test1 Hmm, may be the fact that you are running in 64-bit mode has an impact ? What if you try compiling the code with -m32 ? (and use an appropriate version of python / epydoc) ? Just a shot in the dark... > [........................... > +------------------------------------------------------------------------------------------------- > | File ??, in test1.function > | Warning: Improper paragraph indentation. Ah, well, if docutils can't parse the string properly it's no wonder the translation to html doesn't work. :-) Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From tanguy.fautre at spaceapplications.com Thu Nov 16 17:49:20 2006 From: tanguy.fautre at spaceapplications.com (Tanguy Fautre) Date: Thu, 16 Nov 2006 17:49:20 +0100 Subject: [C++-sig] [Boost.Python] imports and callbacks Message-ID: Hi, Here is an example Python class that will be executed by an embedded Python interpreter: import math; class Subsystem: def __init__(self) : simulation.event.register(self.event_callback) def event_callback(self) : #import math cosine = math.cos(simulation_time) new_subsystem = Subsystem() As you can see, at construction the Subsystem class registers a callback functions via the simulation.event object. The simulation.event object is a C++ object exported via Boost.Python into the main namespace. The simulation.event.register function in C++ has only one argument: a boost::python::object to copy the given callback. Lets say this boost::python::object is named Function. When I call Function(), the callback is correctly called. The interpreter however complains that math.cos is unknown (i.e. ignoring the "import math;" at the beginning of the python code). If I uncomment #import math in the event_callback definition, everything works fine. At first I thought that boost::python::object was ignoring both the local and the main namespaces used by the embedded python interpreter when event_callback was registered. But I realized later that I could still access objects in the main namespace such as the simulation.event object. Is it possible that the top "import math" only affects the local namespace, and that this local namespace is not reused when the callbacked is called through a boost::python::object ? Also, what is the performance impact of the "import math" in the callback? Putting the import inside event_callback is not very annoying, as long as it does not affect performances. Tanguy From ngoodspeed at solidworks.com Thu Nov 16 18:49:05 2006 From: ngoodspeed at solidworks.com (Nat Goodspeed) Date: Thu, 16 Nov 2006 12:49:05 -0500 Subject: [C++-sig] [Boost.Python] imports and callbacks Message-ID: <31E9B8A4BEFAA242B047A736B344578B397240@corp-mail8.solidworks.swk> > -----Original Message----- > From: c++-sig-bounces+ngoodspeed=solidworks.com at python.org [mailto:c++- > sig-bounces+ngoodspeed=solidworks.com at python.org] On Behalf Of Tanguy > Fautre > Sent: Thursday, November 16, 2006 11:49 AM > To: c++-sig at python.org > Subject: [C++-sig] [Boost.Python] imports and callbacks > > The interpreter however complains that math.cos is unknown (i.e. > ignoring the "import math;" at the beginning of the python code). > > If I uncomment #import math in the event_callback definition, everything > works fine. [Nat] When you invoke Python from C++, are you passing the same dict for locals and globals? Whatever you're passing for globals and locals when you evaluate the class definition, are you passing the same two dicts when you re-enter the registered handler? I had a similar issue in which I simply wanted to run a customization script. I prepopulated one dict (I think globals) and passed an empty dict for locals. My inline script code worked fine -- but when I started trying to define functions and classes in the script, the nested code stopped being able to reference my global symbols. I fixed it by passing the same dict for both. From dave at boost-consulting.com Fri Nov 17 00:30:36 2006 From: dave at boost-consulting.com (David Abrahams) Date: Thu, 16 Nov 2006 18:30:36 -0500 Subject: [C++-sig] Creating a python class from c++ References: <20061115181655.53688.qmail@web23111.mail.ird.yahoo.com> <455B5D93.5090700@sympatico.ca> Message-ID: <87y7qbj7fn.fsf@pereiro.luannocracy.com> Stefan Seefeld writes: > James Healey wrote: >> PyFile_AsFile returns a ptr to a file object so that's >> working as it should. >> >> And how do i check the exception? >> >> Do i need to do any thing with the dict that gets >> passed into exec_file? > > No. If the PyFile_AsFile call returns NULL Careful with that one. If Python wasn't compiled with the exact same compiler (and release of that compiler!) and standard lib that you're using to build your extension, you will most likely be trashing memory because the FILE struct layouts and semantics will be different. -- Dave Abrahams Boost Consulting www.boost-consulting.com From seefeld at sympatico.ca Fri Nov 17 00:47:42 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 16 Nov 2006 18:47:42 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <87y7qbj7fn.fsf@pereiro.luannocracy.com> References: <20061115181655.53688.qmail@web23111.mail.ird.yahoo.com> <455B5D93.5090700@sympatico.ca> <87y7qbj7fn.fsf@pereiro.luannocracy.com> Message-ID: <455CF89E.3000605@sympatico.ca> David Abrahams wrote: > Stefan Seefeld writes: > >> James Healey wrote: >>> PyFile_AsFile returns a ptr to a file object so that's >>> working as it should. >>> >>> And how do i check the exception? >>> >>> Do i need to do any thing with the dict that gets >>> passed into exec_file? >> No. If the PyFile_AsFile call returns NULL > > Careful with that one. If Python wasn't compiled with the exact same > compiler (and release of that compiler!) and standard lib that you're > using to build your extension, you will most likely be trashing memory > because the FILE struct layouts and semantics will be different. Yup. This was a typo, I meant to refer to PyRun_File in that mail. (See my followup mail.) Thanks, Stefan -- ...ich hab' noch einen Koffer in Berlin... From tanguy.fautre at spaceapplications.com Fri Nov 17 10:52:56 2006 From: tanguy.fautre at spaceapplications.com (Tanguy Fautre) Date: Fri, 17 Nov 2006 10:52:56 +0100 Subject: [C++-sig] [Boost.Python] imports and callbacks In-Reply-To: <31E9B8A4BEFAA242B047A736B344578B397240@corp-mail8.solidworks.swk> References: <31E9B8A4BEFAA242B047A736B344578B397240@corp-mail8.solidworks.swk> Message-ID: Nat Goodspeed wrote: >> -----Original Message----- >> From: c++-sig-bounces+ngoodspeed=solidworks.com at python.org > [mailto:c++- >> sig-bounces+ngoodspeed=solidworks.com at python.org] On Behalf Of Tanguy >> Fautre >> Sent: Thursday, November 16, 2006 11:49 AM >> To: c++-sig at python.org >> Subject: [C++-sig] [Boost.Python] imports and callbacks >> >> The interpreter however complains that math.cos is unknown (i.e. >> ignoring the "import math;" at the beginning of the python code). >> >> If I uncomment #import math in the event_callback definition, > everything >> works fine. > > [Nat] When you invoke Python from C++, are you passing the same dict for > locals and globals? > > Whatever you're passing for globals and locals when you evaluate the > class definition, are you passing the same two dicts when you re-enter > the registered handler? > > I had a similar issue in which I simply wanted to run a customization > script. I prepopulated one dict (I think globals) and passed an empty > dict for locals. My inline script code worked fine -- but when I started > trying to define functions and classes in the script, the nested code > stopped being able to reference my global symbols. > > I fixed it by passing the same dict for both. Yes, I'm using one global dict for all the scripts, and separate (empty) local dicts for each scripts. I'll try your approach of using the global dict in place of the local one. For that, I'll need to create separate global dicts for each scripts then. Tanguy From tanguy.fautre at spaceapplications.com Fri Nov 17 12:42:31 2006 From: tanguy.fautre at spaceapplications.com (Tanguy Fautre) Date: Fri, 17 Nov 2006 12:42:31 +0100 Subject: [C++-sig] [Boost.Python] imports and callbacks In-Reply-To: References: <31E9B8A4BEFAA242B047A736B344578B397240@corp-mail8.solidworks.swk> Message-ID: Tanguy Fautre wrote: >> Nat Goodspeed wrote: >> >> I fixed it by passing the same dict for both. > > > Yes, I'm using one global dict for all the scripts, and separate (empty) > local dicts for each scripts. > > I'll try your approach of using the global dict in place of the local > one. For that, I'll need to create separate global dicts for each > scripts then. This does the trick. Thanks. Also, by having a separate global dictionary for each script, it avoids one script polluting the namespace of another script. One little catch though, if you read Boost.Python doc (cf. URL below), you would think that python::dict a; python::dict b(a); creates two separate dictionaries, while in fact b is still a reference to a. To do it correctly, I had to do python::dict a; python::dict b(a.copy()); This maybe needs to be clarified in Boost.Python documentation ? http://boost.org/libs/python/doc/tutorial/doc/html/python/object.html Tanguy From dave at boost-consulting.com Fri Nov 17 16:04:37 2006 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 17 Nov 2006 10:04:37 -0500 Subject: [C++-sig] [Boost.Python] imports and callbacks References: <31E9B8A4BEFAA242B047A736B344578B397240@corp-mail8.solidworks.swk> Message-ID: <87r6w2f722.fsf@pereiro.luannocracy.com> Tanguy Fautre writes: > One little catch though, if you read Boost.Python doc (cf. URL below), > you would think that > > python::dict a; > python::dict b(a); > > creates two separate dictionaries, while in fact b is still a reference > to a. To do it correctly, I had to do > > python::dict a; > python::dict b(a.copy()); I think python::dict b(object(a)); should also work. I *think* the copy ctor is different from all the other ctors. Of course it must make such a copy in order to preserve reference semantics when passing these objects around. > This maybe needs to be clarified in Boost.Python documentation ? Probably. Joel? > http://boost.org/libs/python/doc/tutorial/doc/html/python/object.html -- Dave Abrahams Boost Consulting www.boost-consulting.com From charlesf at the-mill.com Fri Nov 17 17:02:52 2006 From: charlesf at the-mill.com (=?UTF-8?B?Q2hhcmxlcyBGbMOoY2hl?=) Date: Fri, 17 Nov 2006 16:02:52 +0000 Subject: [C++-sig] [Boost.Python] shared_ptr Message-ID: <455DDD2C.7000409@the-mill.com> Hello everybody ! I've googled a lot and I wasn't able to find an answer for this, I think, easy beginner question. Let's say I have a that class : /////////////////// // Classe.h /////////////////// class Classe { public: Classe(); }; /////////////////// // Classe.cpp /////////////////// Classe::Classe() { } //////////////////// I'm wrapping it inside my Boost.Python section : class_< Classe >( "Classe" ) ; register_ptr_to_python< boost::shared_ptr >(); I'd like to register a shared_ptr, but I am not able to do it. When I do a register_ptr_to_python< boost::shared_ptr >(), I have that error in my logs : [...] .../pointer_holder.hpp:138: error: invalid conversion from `const void*' to `void*' [...] How can I register a shared_ptr ? Thank you a lot !! -- Charles Fleche The Mill, London From ndbecker2 at gmail.com Fri Nov 17 19:37:29 2006 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 17 Nov 2006 13:37:29 -0500 Subject: [C++-sig] from_python non-compiletime-constant Message-ID: I need to register a from_python conversion where the type object is not a compile constant. I'm trying to write c++ code that will accept a numpy array. AFAICT, the PyTypeObject addresses aren't known at compile time, so can't be used in lvalue_from_pytype template arguments. These pointers can be found at runtime. How do I handle this? From healeyjames at yahoo.co.uk Fri Nov 17 23:26:47 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Fri, 17 Nov 2006 22:26:47 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455CF89E.3000605@sympatico.ca> Message-ID: <311587.56568.qm@web23107.mail.ird.yahoo.com> Ok lets take boost away from what im trying to do, and try to achieve the same thing with just python. Here's my .py file: class MyTest: def TestFunc(): print "Hello From MyTest.TestFunc" And here's my code to handle all this so far: Py_Initialize(); PyObject *pMainModule = PyImport_AddModule( "__main__" ); PyObject *pDict = PyModule_GetDict( pMainModule ); std::string *pythonScript = readPythonScript( "Game.py" ); if( pythonScript != NULL ) { PyRun_String( pythonScript->c_str(), Py_file_input, pDict, pDict ); delete pythonScript; } PyObject* test = PyDict_GetItemString( pDict, "MyTest"); And this is as far as I have got. Any help you can give would be great. Send instant messages to your online friends http://uk.messenger.yahoo.com From healeyjames at yahoo.co.uk Sat Nov 18 12:22:14 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Sat, 18 Nov 2006 11:22:14 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455B1895.7010000@sympatico.ca> Message-ID: <20061118112214.63713.qmail@web23113.mail.ird.yahoo.com> Ok lets take boost away from what im trying to do, and try to achieve the same thing with just python. Here's my .py file: class MyTest: def TestFunc(): print "Hello From MyTest.TestFunc" And here's my code to handle all this so far: Py_Initialize(); PyObject *pMainModule = PyImport_AddModule( "__main__" ); PyObject *pDict = PyModule_GetDict( pMainModule ); std::string *pythonScript = readPythonScript( "Game.py" ); if( pythonScript != NULL ) { PyRun_String( pythonScript->c_str(), Py_file_input, pDict, pDict ); delete pythonScript; } PyObject* test = PyDict_GetItemString( pDict, "MyTest"); And this is as far as I have got. Any help you can give would be great. ___________________________________________________________ All new Yahoo! Mail "The new Interface is stunning in its simplicity and ease of use." - PC Magazine http://uk.docs.yahoo.com/nowyoucan.html From seefeld at sympatico.ca Sat Nov 18 17:00:28 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sat, 18 Nov 2006 11:00:28 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061115212252.71495.qmail@web23103.mail.ird.yahoo.com> References: <20061115212252.71495.qmail@web23103.mail.ird.yahoo.com> Message-ID: <455F2E1C.7070303@sympatico.ca> James Healey wrote: > Ok got the exception catch working and printing out > the error and stack trace. > > ImportError: __import__ not found > > Is the error that I am getting. OK, I think I now understand what's going on: The code I proposed looked like this: namespace bpl = boost::python; bpl::dict global; bpl::exec_file("your_file.py", global, global); Note that 'global' is completely empty, as thus is the environment seen by the script. It appears we need to import the '__main__' module and take its dictionary instead, as that provides some objects we are using: bpl::object main = bpl::import("__main__"); bpl::dict global = main.attr("__dict__"); bpl::exec_file("your_file.py", global, global); That should work. Regards, Stefan PS: And in case you are going to ask where the 'import' function is coming from: I added it at the same time as the exec / exec_file functions, so boost 1.33 doesn't have it yet. Here is a copy: namespace boost { namespace python { object BOOST_PYTHON_DECL import(str name) { // should be 'char const *' but older python versions don't use 'const' yet. char *n = extract(name); handle<> module(borrowed(PyImport_AddModule(n))); return object(module); } } } -- ...ich hab' noch einen Koffer in Berlin... From healeyjames at yahoo.co.uk Sat Nov 18 18:15:09 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Sat, 18 Nov 2006 17:15:09 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455F2E1C.7070303@sympatico.ca> Message-ID: <882034.81216.qm@web23107.mail.ird.yahoo.com> I did ask a few posts ago if any thing should be done with the global variable, but you gave no answer. I also had these 2 lines before: // Retrieve the main module //boost::python::object main = boost::python::import("__main__"); // Retrieve the main module's namespace //boost::python::object global(main.attr("__dict__")); But it didnt compile because I never had the import function. Also this line: bpl::dict global = main.attr("__dict__"); doesnt compile and switched it with: boost::python::object global(main.attr("__dict__")); it gave the error: error C2440: 'initializing' : cannot convert from 'boost::python::api::object_attribute' to 'boost::python::dict' Constructor for class 'boost::python::dict' is declared 'explicit' Every thing works as asked in my original question. Thanks for all your help. ___________________________________________________________ Yahoo! Messenger - with free PC-PC calling and photo sharing. http://uk.messenger.yahoo.com From seefeld at sympatico.ca Sat Nov 18 18:24:43 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sat, 18 Nov 2006 12:24:43 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <882034.81216.qm@web23107.mail.ird.yahoo.com> References: <882034.81216.qm@web23107.mail.ird.yahoo.com> Message-ID: <455F41DB.9090707@sympatico.ca> James Healey wrote: > Also this line: > bpl::dict global = main.attr("__dict__"); > > doesnt compile and switched it with: > boost::python::object global(main.attr("__dict__")); > > it gave the error: > error C2440: 'initializing' : cannot convert from > 'boost::python::api::object_attribute' to > 'boost::python::dict' > Constructor for class 'boost::python::dict' is > declared 'explicit' > > > Every thing works as asked in my original question. Good ! Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From healeyjames at yahoo.co.uk Sun Nov 19 23:31:12 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Sun, 19 Nov 2006 22:31:12 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <455F41DB.9090707@sympatico.ca> Message-ID: <20061119223112.78949.qmail@web23104.mail.ird.yahoo.com> If I have this: class Test { public: int iNumber; int getNumber(void) { return iNumber; } }; BOOST_PYTHON_MODULE( extended_test ) { boost::python::class_("Test") .def( "getNumber", &Test::getNumber ) ; } boost::python::object my_class = global["MyTest"]; How would I go about creating an instance of class Test and passing it to my python class instance? boost::python::object my_instance = my_class(test boost::python::object retn = my_instance.attr("TestFunc")(); Regards. Jimmy. ___________________________________________________________ The all-new Yahoo! Mail goes wherever you go - free your email address from your Internet provider. http://uk.docs.yahoo.com/nowyoucan.html From seefeld at sympatico.ca Sun Nov 19 23:43:48 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sun, 19 Nov 2006 17:43:48 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061119223112.78949.qmail@web23104.mail.ird.yahoo.com> References: <20061119223112.78949.qmail@web23104.mail.ird.yahoo.com> Message-ID: <4560DE24.9020103@sympatico.ca> James Healey wrote: > If I have this: > > class Test > { > public: > int iNumber; > > int getNumber(void) { return iNumber; } > }; > > BOOST_PYTHON_MODULE( extended_test ) > { > boost::python::class_("Test") > .def( "getNumber", &Test::getNumber ) > ; > } > > boost::python::object my_class = global["MyTest"]; > > How would I go about creating an instance of class > Test and passing it to my python class instance? > > boost::python::object my_instance = my_class(test > boost::python::object retn = > my_instance.attr("TestFunc")(); I'm not sure what you are trying to accomplish. Are you asking how to detach the lifetime of the C++ Test instance from the lifetime of the Python Test instance ? In that case it seems most suitable to export a C++ function returning your (C++) Test instance, letting boost.python wrap the existing instance, instead of instantiating the wrapper with a copy of it. You may want to read the docs on call- / return-value policies, too. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From healeyjames at yahoo.co.uk Mon Nov 20 00:07:20 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Sun, 19 Nov 2006 23:07:20 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <4560DE24.9020103@sympatico.ca> Message-ID: <257984.42208.qm@web23110.mail.ird.yahoo.com> Well basically I want to be able to pass a c++ class to a pyhon class and have the python class call the c++ class methods. --- Stefan Seefeld wrote: > James Healey wrote: > > If I have this: > > > > class Test > > { > > public: > > int iNumber; > > > > int getNumber(void) { return iNumber; } > > }; > > > > BOOST_PYTHON_MODULE( extended_test ) > > { > > boost::python::class_("Test") > > .def( "getNumber", &Test::getNumber ) > > ; > > } > > > > boost::python::object my_class = global["MyTest"]; > > > > How would I go about creating an instance of class > > Test and passing it to my python class instance? > > > > boost::python::object my_instance = my_class(test > > boost::python::object retn = > > my_instance.attr("TestFunc")(); > > I'm not sure what you are trying to accomplish. Are > you asking how > to detach the lifetime of the C++ Test instance from > the lifetime of > the Python Test instance ? > > In that case it seems most suitable to export a C++ > function > returning your (C++) Test instance, letting > boost.python wrap the existing > instance, instead of instantiating the wrapper with > a copy of it. > You may want to read the docs on call- / > return-value policies, too. > > > HTH, > Stefan > > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > Send instant messages to your online friends http://uk.messenger.yahoo.com From seefeld at sympatico.ca Mon Nov 20 00:29:42 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sun, 19 Nov 2006 18:29:42 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <257984.42208.qm@web23110.mail.ird.yahoo.com> References: <257984.42208.qm@web23110.mail.ird.yahoo.com> Message-ID: <4560E8E6.30006@sympatico.ca> James Healey wrote: > Well basically I want to be able to pass a c++ class > to a pyhon class and have the python class call the > c++ class methods. I take it you mean 'instance' whenever you say 'class', right ? Does what I suggest not work ? Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From bernhard.maeder at zkb.ch Mon Nov 20 08:30:28 2006 From: bernhard.maeder at zkb.ch (bernhard.maeder at zkb.ch) Date: Mon, 20 Nov 2006 08:30:28 +0100 Subject: [C++-sig] Wrapping a base class' method Message-ID: Hello all I'm trying to export some base class' methods with the derived class directly. See the following code: // ----------------------------------------------------- #include struct my_base_class { int const & get_base_i() const { return i_; } int i_; }; struct my_class : my_base_class { int const & get_i() const { return i_; } int i_; }; using namespace boost::python; BOOST_PYTHON_MODULE(_test) { class_("MyClass") .add_property("i", make_function(&my_class::get_i, return_value_policy())) .add_property("basei", make_function(&my_class::get_base_i, return_value_policy())) ; } // ----------------------------------------------------- Now python throws the following at me: h[ 1] >>> from _test import * h[ 1] >>> MyClass().basei Traceback (most recent call last): File "", line 1, in ? Boost.Python.ArgumentError: Python argument types in None.None(MyClass) did not match C++ signature: None(my_base_class {lvalue}) So, my question is: Am I not supposed to do this at all? The same seems to work flawlessly when returning by value instead of by reference.... Thanks for your input Bernhard ___________________________________________________________________ Disclaimer: Diese Mitteilung ist nur fuer die Empfaengerin / den Empfaenger bestimmt. Fuer den Fall, dass sie von nichtberechtigten Personen empfangen wird, bitten wir diese hoeflich, die Mitteilung an die ZKB zurueckzusenden und anschliessend die Mitteilung mit allen Anhaengen sowie allfaellige Kopien zu vernichten bzw. zu loeschen. Der Gebrauch der Information ist verboten. This message is intended only for the named recipient and may contain confidential or privileged information. If you have received it in error, please advise the sender by return e-mail and delete this message and any attachments. Any unauthorised use or dissemination of this information is strictly prohibited. -------------- next part -------------- An HTML attachment was scrubbed... URL: From charlesf at the-mill.com Mon Nov 20 11:22:29 2006 From: charlesf at the-mill.com (=?ISO-8859-1?Q?Charles_Fl=E8che?=) Date: Mon, 20 Nov 2006 10:22:29 +0000 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <455DDD2C.7000409@the-mill.com> References: <455DDD2C.7000409@the-mill.com> Message-ID: <456181E5.8060005@the-mill.com> That kind of question has already been posted a few month ago, and had no answer. I'd like to know if it's because it's a 100% newbie question and you are tired of answer that (if so, please point me to the FAQ so I could RTFM), or if there is a real technical problem behind that. Thank you a lot ! -- Charles Fleche The Mill, London From kir at lapshin.net Mon Nov 20 11:32:08 2006 From: kir at lapshin.net (Kirill Lapshin) Date: Mon, 20 Nov 2006 13:32:08 +0300 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <456181E5.8060005@the-mill.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> Message-ID: <45618428.8050904@lapshin.net> Not sure if that is the right solution, but I am tackling this problem in a following way: namespace boost{ namespace python{ template inline T* get_pointer( boost::shared_ptr const& p){ return const_cast(p.get()); } template struct pintee< boost::shared_ptr >{ typedef T type; }; }} and later on boost::python::register_ptr_to_python< boost::shared_ptr >(); Looks more like workaround to me, so if anyone can propose better solution, I am all ears. Charles Fl?che wrote: > That kind of question has already been posted a few month ago, and had > no answer. I'd like to know if it's because it's a 100% newbie question > and you are tired of answer that (if so, please point me to the FAQ so I > could RTFM), or if there is a real technical problem behind that. > > Thank you a lot ! > From charlesf at the-mill.com Mon Nov 20 11:34:52 2006 From: charlesf at the-mill.com (=?ISO-8859-1?Q?Charles_Fl=E8che?=) Date: Mon, 20 Nov 2006 10:34:52 +0000 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <45618428.8050904@lapshin.net> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> Message-ID: <456184CC.8090208@the-mill.com> > > Looks more like workaround to me, so if anyone can propose better > solution, I am all ears. Ok for the workaround, but I'm going to give it a try ! Thank you a lot, Kirill ! -- Charles Fleche The Mill, London From charlesf at the-mill.com Mon Nov 20 12:26:28 2006 From: charlesf at the-mill.com (=?ISO-8859-1?Q?Charles_Fl=E8che?=) Date: Mon, 20 Nov 2006 11:26:28 +0000 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <456184CC.8090208@the-mill.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> <456184CC.8090208@the-mill.com> Message-ID: <456190E4.8050304@the-mill.com> > Ok for the workaround, but I'm going to give it a try ! I've tried it, but if now it compiles well, I have a python error at runtime : Traceback (most recent call last): File "", line 1, in ? Boost.Python.ArgumentError: Python argument types in Classd.f_const_shared_ptr(Classd, Classd) did not match C++ signature: f_const_shared_ptr(Classd {lvalue}, boost::shared_ptr) These are the files : // Classd.h #ifndef CLASSD_H #define CLASSD_H #include #include using namespace boost; class Classd { public: Classd(); std::string type(); shared_ptr factory(); shared_ptr factory_const(); void f_object( Classd ); void f_const_object( const Classd ); void f_shared_ptr( shared_ptr ); void f_const_shared_ptr( shared_ptr ); protected: void log( std::string ); }; #endif // Classd.cpp #include "Classd.h" #include using namespace std; using namespace boost; Classd::Classd() { } string Classd::type() { return string( "I'm a Classd" ); } shared_ptr Classd::factory() { shared_ptr ret( new Classd ); return ret; } shared_ptr Classd::factory_const() { shared_ptr ret( new Classd ); return ret; } void Classd::f_object( Classd ) { log( "f_object" ); } void Classd::f_const_object( const Classd ) { log( "f_const_object" ); } void Classd::f_shared_ptr( shared_ptr ) { log( "f_shared_ptr" ); } void Classd::f_const_shared_ptr( shared_ptr ) { log( "f_const_shared_ptr" ); } void Classd::log( string l ) { cout << "Classd : " << l << endl; } template class shared_ptr; template class shared_ptr; // Wrap.cpp -- trimmed down version with just Classd #include using namespace boost::python; #include "Classd.h" namespace boost { namespace python { template inline T* get_pointer( boost::shared_ptr const& p) { return const_cast(p.get()); } template struct pointee< boost::shared_ptr > { typedef T type; }; } } BOOST_PYTHON_MODULE(OwnTest) { class_< Classd >( "Classd" ) .def( "type", &Classd::type ) .def( "factory", &Classd::factory ) .def( "factory_const", &Classd::factory_const ) .def( "f_object", &Classd::f_object ) .def( "f_const_object", &Classd::f_const_object ) .def( "f_shared_ptr", &Classd::f_shared_ptr ) .def( "f_const_shared_ptr", &Classd::f_const_shared_ptr ) ; register_ptr_to_python< boost::shared_ptr< Classd > >(); register_ptr_to_python< boost::shared_ptr< const Classd > >(); } // Python log >>> a.factory() >>> a.factory_const() >>> a.f_object( a ) Classd : f_object >>> a.f_const_object( a ) Classd : f_const_object >>> a.f_shared_ptr( a ) Classd : f_shared_ptr >>> a.f_const_shared_ptr( a ) Traceback (most recent call last): File "", line 1, in ? Boost.Python.ArgumentError: Python argument types in Classd.f_const_shared_ptr(Classd, Classd) did not match C++ signature: f_const_shared_ptr(Classd {lvalue}, boost::shared_ptr) -- Charles Fleche From roman.yakovenko at gmail.com Mon Nov 20 12:29:42 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 20 Nov 2006 13:29:42 +0200 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <456190E4.8050304@the-mill.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> <456184CC.8090208@the-mill.com> <456190E4.8050304@the-mill.com> Message-ID: <7465b6170611200329h73a04cdfsc5cd2fae09082e7f@mail.gmail.com> On 11/20/06, Charles Fl?che wrote: > > > Ok for the workaround, but I'm going to give it a try ! > > > I've tried it, but if now it compiles well, I have a python error at > runtime : > > Traceback (most recent call last): > File "", line 1, in ? > Boost.Python.ArgumentError: Python argument types in > Classd.f_const_shared_ptr(Classd, Classd) > did not match C++ signature: > f_const_shared_ptr(Classd {lvalue}, boost::shared_ptr) > > > These are the files : > > // Classd.h > > #ifndef CLASSD_H > #define CLASSD_H > > #include > > #include > using namespace boost; > > class Classd > { > public: > Classd(); > std::string type(); > shared_ptr factory(); > shared_ptr factory_const(); > > void f_object( Classd ); > void f_const_object( const Classd ); > void f_shared_ptr( shared_ptr ); > void f_const_shared_ptr( shared_ptr ); > > protected: > void log( std::string ); > > }; > > #endif > > > > > // Classd.cpp > > #include "Classd.h" > > #include > using namespace std; > using namespace boost; > > Classd::Classd() > { > } > > string Classd::type() > { > return string( "I'm a Classd" ); > } > > shared_ptr Classd::factory() > { > shared_ptr ret( new Classd ); > return ret; > } > > shared_ptr Classd::factory_const() > { > shared_ptr ret( new Classd ); > return ret; > } > > void Classd::f_object( Classd ) > { > log( "f_object" ); > } > > void Classd::f_const_object( const Classd ) > { > log( "f_const_object" ); > } > > void Classd::f_shared_ptr( shared_ptr ) > { > log( "f_shared_ptr" ); > } > > void Classd::f_const_shared_ptr( shared_ptr ) > { > log( "f_const_shared_ptr" ); > } > > void Classd::log( string l ) > { > cout << "Classd : " << l << endl; > } > > template class shared_ptr; > template class shared_ptr; > > > > > > // Wrap.cpp -- trimmed down version with just Classd > > #include > using namespace boost::python; > > #include "Classd.h" > > namespace boost > { > namespace python > { > > template inline T* get_pointer( > boost::shared_ptr const& p) > { > return const_cast(p.get()); > } > > template struct pointee< boost::shared_ptr > > { > typedef T type; > }; > } > } > > > BOOST_PYTHON_MODULE(OwnTest) > { > class_< Classd >( "Classd" ) > .def( "type", &Classd::type ) > .def( "factory", &Classd::factory ) > .def( "factory_const", &Classd::factory_const ) > .def( "f_object", &Classd::f_object ) > .def( "f_const_object", &Classd::f_const_object ) > .def( "f_shared_ptr", &Classd::f_shared_ptr ) > .def( "f_const_shared_ptr", &Classd::f_const_shared_ptr ) > ; > > register_ptr_to_python< boost::shared_ptr< Classd > >(); > register_ptr_to_python< boost::shared_ptr< const Classd > >(); > > } > > > > > // Python log > > >>> a.factory() > > >>> a.factory_const() > > >>> a.f_object( a ) > Classd : f_object > >>> a.f_const_object( a ) > Classd : f_const_object > >>> a.f_shared_ptr( a ) > Classd : f_shared_ptr > >>> a.f_const_shared_ptr( a ) > Traceback (most recent call last): > File "", line 1, in ? > Boost.Python.ArgumentError: Python argument types in > Classd.f_const_shared_ptr(Classd, Classd) > did not match C++ signature: > f_const_shared_ptr(Classd {lvalue}, boost::shared_ptr) I think you should also register implicit conversion between smart pointers http://boost.org/libs/python/doc/v2/implicit.html#implicitly_convertible-spec -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From charlesf at the-mill.com Mon Nov 20 12:41:38 2006 From: charlesf at the-mill.com (=?ISO-8859-1?Q?Charles_Fl=E8che?=) Date: Mon, 20 Nov 2006 11:41:38 +0000 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <7465b6170611200329h73a04cdfsc5cd2fae09082e7f@mail.gmail.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> <456184CC.8090208@the-mill.com> <456190E4.8050304@the-mill.com> <7465b6170611200329h73a04cdfsc5cd2fae09082e7f@mail.gmail.com> Message-ID: <45619472.5090600@the-mill.com> > I think you should also register implicit conversion between smart pointers > http://boost.org/libs/python/doc/v2/implicit.html#implicitly_convertible-spec Thank you a lot Kirill and Roman, it's working well now ! -- Charles Fleche From roman.yakovenko at gmail.com Mon Nov 20 13:03:38 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 20 Nov 2006 14:03:38 +0200 Subject: [C++-sig] [ANN]Python-Ogre bindings Message-ID: <7465b6170611200403q7b89babdl88131a9910b0393a@mail.gmail.com> Hi. I am please to announce the second release of Python-Ogre. Python-Ogre is a set of Python bindings to the next libraries: * Ogre3d * CEGUI * Newton * ODE * OIS All libraries were exposed to Python using Boost.Python and Py++. Python-Ogre home page: http://python-ogre.python-hosting.com/ Py++ home page: http://language-binding.net/pyplusplus/pyplusplus.html -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From Tessore at stud.uni-heidelberg.de Mon Nov 20 13:52:32 2006 From: Tessore at stud.uni-heidelberg.de (Nicolas Tessore) Date: Mon, 20 Nov 2006 13:52:32 +0100 Subject: [C++-sig] Split_module and file names Message-ID: <4561A510.5000505@stud.uni-heidelberg.de> Hello, I stumbled into this seemingly stupid problem, but don't know a way out. I have got pretty much everything working in my setup, except for the fact that the wrapper file is 50k lines big and cl.exe crashes after some minutes compiling it. I read the Best Practices article and started to include caching, and finally split_module into my generator. Now the creation fails because of filename length. 'vector_less_std_scope_vector_less_unsigned_short_comma__std_scope_allocator _less_unsigned_short_grate___grate__comma__std_scope_allocator_less_std _scope_vector_less_unsigned_short_comma__std_scope_allocator_less_ unsigned_short_grate___grate___grate___grate_.pypp.hpp' is a 266 characters filename, and it is one of the rather short. It's just a vector > > . I have a ton of more nested containers, and cannot manually alias them all. Then, I tried to make a typedef vector > > vector_vector_ushort; but this changed nothing for me. So it may once again be proof of my ignorance, but could you point me in the right direction? It'd be eternally grateful :) N. From roman.yakovenko at gmail.com Mon Nov 20 16:19:50 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 20 Nov 2006 17:19:50 +0200 Subject: [C++-sig] Split_module and file names In-Reply-To: <4561A510.5000505@stud.uni-heidelberg.de> References: <4561A510.5000505@stud.uni-heidelberg.de> Message-ID: <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> On 11/20/06, Nicolas Tessore wrote: > Now the creation fails because of filename length. > ... > I have a ton of more nested > containers, and cannot manually alias them all. The solution is to create some function that will create an alias from an instantiation of std container. Obviously Py++ does if for you, but the names it creates are very long and ugly. You can do something better. Take a look on container traits classes: http://tinyurl.com/yeezdc . These classes will help you to extract value_type( mapped_type ) from the container. ( source code: http://tinyurl.com/yeco7e ) Use pygccxml.declaration.all_container_traits variable. It defines a list of all container traits classes Now the code is pretty trivial: def find_out_container_traits( cls ): for ct in pygccxml.declaration.all_container_traits: if ct.is_my_case( cls ): return ct else: return None def mangle( cls, ct ): element_type = ct.element_type( cls ) cls.rename( .... ) mb = module_builder_t( ... ) for cls in mb.classes(): ct = find_out_container_traits( cls ) if ct: mangle( cls, ct ) This should work. > Then, I tried to make a > > typedef vector > > vector_vector_ushort; > > but this changed nothing for me. I think that the reason is that too many different typedefs for the instantiation > So it may once again be proof of my ignorance, but could you point me in > the right direction? Is this the right direction? -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From wz_ at gmx.net Mon Nov 20 16:54:29 2006 From: wz_ at gmx.net (Nicolas Tessore) Date: Mon, 20 Nov 2006 16:54:29 +0100 Subject: [C++-sig] Split_module and file names In-Reply-To: <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> Message-ID: <4561CFB5.6080307@gmx.net> Thanks a lot: pygccxml.declaration.all_container_traits was exactly what I had been looking for. (I should get used to "container" for templated types.) Thanks again! N. From roman.yakovenko at gmail.com Mon Nov 20 19:26:18 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 20 Nov 2006 20:26:18 +0200 Subject: [C++-sig] Split_module and file names In-Reply-To: <4561CFB5.6080307@gmx.net> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> <4561CFB5.6080307@gmx.net> Message-ID: <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> On 11/20/06, Nicolas Tessore wrote: > Thanks a lot: > > pygccxml.declaration.all_container_traits > > was exactly what I had been looking for. > > (I should get used to "container" for templated types.) It seems to me that you are surprised by the terminology I use, am I right? If so can you explain why? I'll be glad to fix it. Thanks. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From wz_ at gmx.net Mon Nov 20 19:47:20 2006 From: wz_ at gmx.net (Nicolas Tessore) Date: Mon, 20 Nov 2006 19:47:20 +0100 Subject: [C++-sig] Split_module and file names In-Reply-To: <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> <4561CFB5.6080307@gmx.net> <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> Message-ID: <4561F838.1090400@gmx.net> Roman Yakovenko, 20.11.2006 19:26 > On 11/20/06, Nicolas Tessore wrote: >> Thanks a lot: >> >> pygccxml.declaration.all_container_traits >> >> was exactly what I had been looking for. >> >> (I should get used to "container" for templated types.) > > It seems to me that you are surprised by the terminology I use, am I right? > If so can you explain why? I'll be glad to fix it. > > Thanks. > No, I was just too narrow-minded to search for the obvious phrase "container". My bad! N. From roman.yakovenko at gmail.com Mon Nov 20 19:56:25 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 20 Nov 2006 20:56:25 +0200 Subject: [C++-sig] Split_module and file names In-Reply-To: <4561F838.1090400@gmx.net> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> <4561CFB5.6080307@gmx.net> <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> <4561F838.1090400@gmx.net> Message-ID: <7465b6170611201056u76524947gaae8103e9626ed78@mail.gmail.com> On 11/20/06, Nicolas Tessore wrote: > Roman Yakovenko, 20.11.2006 19:26 > > On 11/20/06, Nicolas Tessore wrote: > >> Thanks a lot: > >> > >> pygccxml.declaration.all_container_traits > >> > >> was exactly what I had been looking for. > >> > >> (I should get used to "container" for templated types.) > > > > It seems to me that you are surprised by the terminology I use, am I right? > > If so can you explain why? I'll be glad to fix it. > > > > Thanks. > > > > No, I was just too narrow-minded to search for the obvious phrase > "container". My bad! I could be wrong, but std uses "containers" terminology. .NET for example uses "collection" word. So, I thought it should be clear what I mean. It has nothing to do with templates. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From roman.yakovenko at gmail.com Mon Nov 20 21:29:25 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Mon, 20 Nov 2006 22:29:25 +0200 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <45619472.5090600@the-mill.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> <456184CC.8090208@the-mill.com> <456190E4.8050304@the-mill.com> <7465b6170611200329h73a04cdfsc5cd2fae09082e7f@mail.gmail.com> <45619472.5090600@the-mill.com> Message-ID: <7465b6170611201229w3648c1e1ubeb766895ac412e2@mail.gmail.com> On 11/20/06, Charles Fl?che wrote: > > > I think you should also register implicit conversion between smart pointers > > http://boost.org/libs/python/doc/v2/implicit.html#implicitly_convertible-spec > > > Thank you a lot Kirill and Roman, it's working well now ! I just created and tested a complete solution to the problem: http://pygccxml.svn.sourceforge.net/viewvc/pygccxml/pyplusplus_dev/docs/bpl_lessons_learned/shared_ptr/solution.cpp?view=markup http://pygccxml.svn.sourceforge.net/viewvc/pygccxml/pyplusplus_dev/docs/bpl_lessons_learned/shared_ptr/test.py?view=markup Hope this will be helpful for other too. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From Tessore at stud.uni-heidelberg.de Tue Nov 21 00:16:33 2006 From: Tessore at stud.uni-heidelberg.de (Nicolas Tessore) Date: Tue, 21 Nov 2006 00:16:33 +0100 Subject: [C++-sig] Split_module and file names In-Reply-To: <7465b6170611201056u76524947gaae8103e9626ed78@mail.gmail.com> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> <4561CFB5.6080307@gmx.net> <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> <4561F838.1090400@gmx.net> <7465b6170611201056u76524947gaae8103e9626ed78@mail.gmail.com> Message-ID: <45623751.6070402@stud.uni-heidelberg.de> Roman Yakovenko, 20.11.2006 19:56 > I could be wrong, but std uses "containers" terminology. .NET for example uses > "collection" word. So, I thought it should be clear what I mean. It > has nothing to > do with templates. > Of course, you are right. I just failed to realize the above. Anyway, there is still a problem with the new approach: I extended it to all templates, and failed, somehow, neither the container approach nor the templates.is_instantiation method seems to be able to catch the map type (and list as well, I think): ------------------------------------------------------------------------ # Function to rename the STL containers def rename_containers( cls ): class_trait = None // check there are really some map containers if cls.name.startswith("map"): print cls.name for ct in declarations.all_container_traits: if ct.is_my_case( cls ): class_trait = ct if not (class_trait or declarations.templates.is_instantiation(cls.decl_string)): return // no map container ever makes it here - vector does! print cls.name cls.rename(TemplateAlias(cls.decl_string)) ... # Rename the container types classes = mb.classes() map( rename_containers, classes ) ------------------------------------------------------------------------ From what I understand, the declarations.templates.is_instantiation(cls.decl_string) line alone should be able to catch whatever template type I run into. What am I missing this time? N. From kir at lapshin.net Mon Nov 20 11:32:08 2006 From: kir at lapshin.net (Kirill Lapshin) Date: Mon, 20 Nov 2006 13:32:08 +0300 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <456181E5.8060005@the-mill.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> Message-ID: <45618428.8050904@lapshin.net> Not sure if that is the right solution, but I am tackling this problem in a following way: namespace boost{ namespace python{ template inline T* get_pointer( boost::shared_ptr const& p){ return const_cast(p.get()); } template struct pintee< boost::shared_ptr >{ typedef T type; }; }} and later on boost::python::register_ptr_to_python< boost::shared_ptr >(); Looks more like workaround to me, so if anyone can propose better solution, I am all ears. Charles Fl?che wrote: > That kind of question has already been posted a few month ago, and had > no answer. I'd like to know if it's because it's a 100% newbie question > and you are tired of answer that (if so, please point me to the FAQ so I > could RTFM), or if there is a real technical problem behind that. > > Thank you a lot ! > From roman.yakovenko at gmail.com Tue Nov 21 07:33:07 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 21 Nov 2006 08:33:07 +0200 Subject: [C++-sig] Split_module and file names In-Reply-To: <45623751.6070402@stud.uni-heidelberg.de> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> <4561CFB5.6080307@gmx.net> <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> <4561F838.1090400@gmx.net> <7465b6170611201056u76524947gaae8103e9626ed78@mail.gmail.com> <45623751.6070402@stud.uni-heidelberg.de> Message-ID: <7465b6170611202233w50c7a1d2k4490327aa25db85a@mail.gmail.com> On 11/21/06, Nicolas Tessore wrote: > Roman Yakovenko, 20.11.2006 19:56 > > I could be wrong, but std uses "containers" terminology. .NET for example uses > > "collection" word. So, I thought it should be clear what I mean. It > > has nothing to > > do with templates. > > > > Of course, you are right. I just failed to realize the above. > > Anyway, there is still a problem with the new approach: I extended it to > all templates, and failed, somehow, neither the container approach nor > the templates.is_instantiation method seems to be able to catch the > map type (and list as well, I think): Strange, this test ( http://tinyurl.com/y2a5g6 ) shows that it does work for map and vector ( not list, but still it is not too different ) > ------------------------------------------------------------------------ > > # Function to rename the STL containers > def rename_containers( cls ): > class_trait = None > > // check there are really some map containers > if cls.name.startswith("map"): > print cls.name > > for ct in declarations.all_container_traits: > if ct.is_my_case( cls ): > class_trait = ct > > if not (class_trait or > declarations.templates.is_instantiation(cls.decl_string)): > return > > // no map container ever makes it here - vector does! > print cls.name > cls.rename(TemplateAlias(cls.decl_string)) > > ... > > # Rename the container types > classes = mb.classes() > map( rename_containers, classes ) > > ------------------------------------------------------------------------ > > From what I understand, the > declarations.templates.is_instantiation(cls.decl_string) > line alone should be able to catch whatever template type I run into. Don't use "cls.decl_string" but cls.name. pygccxml implements small and naive parser for C++ templates. It works most of the time. It does not able to parser string like x::y::z< a, b, c >, but z< a, b, c >. P.S. If it does not help, can you come up with small test case that reproduce the problem? -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From charlesf at the-mill.com Tue Nov 21 10:33:31 2006 From: charlesf at the-mill.com (=?ISO-8859-1?Q?Charles_Fl=E8che?=) Date: Tue, 21 Nov 2006 09:33:31 +0000 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <7465b6170611201229w3648c1e1ubeb766895ac412e2@mail.gmail.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> <456184CC.8090208@the-mill.com> <456190E4.8050304@the-mill.com> <7465b6170611200329h73a04cdfsc5cd2fae09082e7f@mail.gmail.com> <45619472.5090600@the-mill.com> <7465b6170611201229w3648c1e1ubeb766895ac412e2@mail.gmail.com> Message-ID: <4562C7EB.6010504@the-mill.com> > I just created and tested a complete solution to the problem: > http://pygccxml.svn.sourceforge.net/viewvc/pygccxml/pyplusplus_dev/docs/bpl_lessons_learned/shared_ptr/solution.cpp?view=markup > http://pygccxml.svn.sourceforge.net/viewvc/pygccxml/pyplusplus_dev/docs/bpl_lessons_learned/shared_ptr/test.py?view=markup > Excellent Roman ! I'm sure it will be really helpful ! -- Charles Fleche From healeyjames at yahoo.co.uk Tue Nov 21 20:58:53 2006 From: healeyjames at yahoo.co.uk (James Healey) Date: Tue, 21 Nov 2006 19:58:53 +0000 (GMT) Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <4560E8E6.30006@sympatico.ca> Message-ID: <20061121195854.5745.qmail@web23115.mail.ird.yahoo.com> Im trying to call a python function which is not in a class: exec_file("Data\\Script\\Editor.py", global, global); boost::python::object func = global["OnClick"]; func(); But it's falling over when I call the object, global returns a valid object and if i look at func in the debugger it says it's a function. It falls over when calling: // This conversion *must not* be done in the same expression as // the call, because, in the special case where the result is a // reference a Python object which was created by converting a C++ // argument for passing to PyEval_CallFunction, its reference // count will be 2 until the end of the full expression containing // the conversion, and that interferes with dangling // pointer/reference detection. converter::return_from_python converter; The ref count of func is 2 is that helps. ___________________________________________________________ Try the all-new Yahoo! Mail. "The New Version is radically easier to use" ? The Wall Street Journal http://uk.docs.yahoo.com/nowyoucan.html From seefeld at sympatico.ca Tue Nov 21 21:18:03 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 21 Nov 2006 15:18:03 -0500 Subject: [C++-sig] Creating a python class from c++ In-Reply-To: <20061121195854.5745.qmail@web23115.mail.ird.yahoo.com> References: <20061121195854.5745.qmail@web23115.mail.ird.yahoo.com> Message-ID: <45635EFB.8050706@sympatico.ca> James Healey wrote: > Im trying to call a python function which is not in a > class: > > exec_file("Data\\Script\\Editor.py", global, global); > > boost::python::object func = global["OnClick"]; > func(); > > But it's falling over when I call the object, global > returns a valid object and if i look at func in the > debugger it says it's a function. > > It falls over when calling: ...what ? > // This conversion *must not* be done in the same > expression as > // the call, because, in the special case where > the result is a > // reference a Python object which was created by > converting a C++ > // argument for passing to PyEval_CallFunction, > its reference > // count will be 2 until the end of the full > expression containing > // the conversion, and that interferes with > dangling > // pointer/reference detection. > converter::return_from_python converter; > > The ref count of func is 2 is that helps. Sorry, I don't see any call here. Further, if you really expect anybody to help you please provide a minimal self-contained test case that allows others to reproduce the problem. Not to mention that you didn't tell us what platform you are working on, what toolchain, etc. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From pbaillargeon at innobec.com Tue Nov 21 22:27:10 2006 From: pbaillargeon at innobec.com (Pierre Baillargeon) Date: Tue, 21 Nov 2006 16:27:10 -0500 Subject: [C++-sig] Crash during exception translation using Intel Compiler 9.1 and optimized builds Message-ID: <45636F2E.7090700@innobec.com> We're using the framework to translate C++ exception to Python exceptions. The code works in debug builds but crashes in optimized builds. Were using Intel Compiler 9.1 on Windows. Has anyone experienced this? Any possible workaround? The symptoms are: - a crash under _is_exception() in MSVCR80.DLL, called from handle_exception_impl(). - The bottom of the stack is obviously bad: below _is_exception_typeof() we find tanhf (float's hyperbolic tangent? Microsoft obviously found a new type-system theorem involving high-level maths), then a long boost template and 0x0. - The arguments received in the long boost::python type (which I cannot see because the name is too long for windbg) are a0, a1 and f, and f is 0 (which might explain to jump to 0x0). Currently the only work-around we've found is to disable the exception translation. From the look of the stack, it seems that the problem is in the linked list of translators. Could it be an order-of-initialization issue? Or a temporary value that should stick around or that the compiler mistakenly optimizes away? From Tessore at stud.uni-heidelberg.de Wed Nov 22 23:36:07 2006 From: Tessore at stud.uni-heidelberg.de (Nicolas Tessore) Date: Wed, 22 Nov 2006 23:36:07 +0100 Subject: [C++-sig] Split_module and file names In-Reply-To: <7465b6170611202233w50c7a1d2k4490327aa25db85a@mail.gmail.com> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> <4561CFB5.6080307@gmx.net> <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> <4561F838.1090400@gmx.net> <7465b6170611201056u76524947gaae8103e9626ed78@mail.gmail.com> <45623751.6070402@stud.uni-heidelberg.de> <7465b6170611202233w50c7a1d2k4490327aa25db85a@mail.gmail.com> Message-ID: <4564D0D7.3030505@stud.uni-heidelberg.de> Roman Yakovenko, 21.11.2006 07:33 > Strange, this test ( http://tinyurl.com/y2a5g6 ) shows that it does > work for map and vector > ( not list, but still it is not too different ) I also cannot see why it should not be working for me! > Don't use "cls.decl_string" but cls.name. pygccxml implements small > and naive parser > for C++ templates. It works most of the time. It does not able to > parser string like > x::y::z< a, b, c >, but z< a, b, c >. I found that both .name and .decl_string don't have the initial scope, and both don't work for me. > P.S. If it does not help, can you come up with small test case that > reproduce the problem? That's the most absurd thing of it all: I tryed if not declarations.templates.is_instantiation(cls.name): print cls.name and then copied the output string, and manually tried it with print declarations.templates.is_instantiation("map<... >") which would always show as True. I'm confused, seems like I have to catch the maps manually with a cls.name.startswith("map") or something alike. N. From roman.yakovenko at gmail.com Thu Nov 23 13:01:30 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 23 Nov 2006 14:01:30 +0200 Subject: [C++-sig] Split_module and file names In-Reply-To: <4564D0D7.3030505@stud.uni-heidelberg.de> References: <4561A510.5000505@stud.uni-heidelberg.de> <7465b6170611200719y4188f2ffnebd6e22b8f45b088@mail.gmail.com> <4561CFB5.6080307@gmx.net> <7465b6170611201026t17cb651fofcd9b40ea3d8c9ef@mail.gmail.com> <4561F838.1090400@gmx.net> <7465b6170611201056u76524947gaae8103e9626ed78@mail.gmail.com> <45623751.6070402@stud.uni-heidelberg.de> <7465b6170611202233w50c7a1d2k4490327aa25db85a@mail.gmail.com> <4564D0D7.3030505@stud.uni-heidelberg.de> Message-ID: <7465b6170611230401q6d92b2c6w50a0f2d4efa760f6@mail.gmail.com> On 11/23/06, Nicolas Tessore wrote: > Roman Yakovenko, 21.11.2006 07:33 > > > Strange, this test ( http://tinyurl.com/y2a5g6 ) shows that it does > > work for map and vector > > ( not list, but still it is not too different ) > > I also cannot see why it should not be working for me! > > > Don't use "cls.decl_string" but cls.name. pygccxml implements small > > and naive parser > > for C++ templates. It works most of the time. It does not able to > > parser string like > > x::y::z< a, b, c >, but z< a, b, c >. > > I found that both .name and .decl_string don't have the initial scope, > and both don't work for me. > > > P.S. If it does not help, can you come up with small test case that > > reproduce the problem? > > That's the most absurd thing of it all: I tryed > > if not declarations.templates.is_instantiation(cls.name): > print cls.name > > and then copied the output string, and manually tried it with > > print declarations.templates.is_instantiation("map<... >") > > which would always show as True. > > I'm confused, seems like I have to catch the maps manually with a > cls.name.startswith("map") or something alike. Wait a little. Can you send me privately zipped GCC-XML generated file and small script that shows your problem? I'd like to understand the problem. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From rwgk at yahoo.com Thu Nov 23 18:37:10 2006 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Thu, 23 Nov 2006 09:37:10 -0800 (PST) Subject: [C++-sig] Wrapping a base class' method Message-ID: <20061123173710.14449.qmail@web31115.mail.mud.yahoo.com> Write a thin wrapper and .add_property that, e.g. (untested) int get_base_i_directly(my_class const& self) { return self.get_base_i(); } ... .add_property("basei", make_function(get_base_i_directly)) This way Boost.Python only "sees" my_class in the signature. ----- Original Message ---- From: "bernhard.maeder at zkb.ch" To: c++-sig at python.org Sent: Sunday, November 19, 2006 11:30:28 PM Subject: [C++-sig] Wrapping a base class' method Hello all I'm trying to export some base class' methods with the derived class directly. See the following code: // ----------------------------------------------------- #include struct my_base_class { int const & get_base_i() const { return i_; } int i_; }; struct my_class : my_base_class { int const & get_i() const { return i_; } int i_; }; using namespace boost::python; BOOST_PYTHON_MODULE(_test) { class_("MyClass") .add_property("i", make_function(&my_class::get_i, return_value_policy())) .add_property("basei", make_function(&my_class::get_base_i, return_value_policy())) ; } // ----------------------------------------------------- Now python throws the following at me: h[ 1] >>> from _test import * h[ 1] >>> MyClass().basei Traceback (most recent call last): File "", line 1, in ? Boost.Python.ArgumentError: Python argument types in None.None(MyClass) did not match C++ signature: None(my_base_class {lvalue}) So, my question is: Am I not supposed to do this at all? The same seems to work flawlessly when returning by value instead of by reference.... Thanks for your input Bernhard ___________________________________________________________________ Disclaimer: Diese Mitteilung ist nur fuer die Empfaengerin / den Empfaenger bestimmt. Fuer den Fall, dass sie von nichtberechtigten Personen empfangen wird, bitten wir diese hoeflich, die Mitteilung an die ZKB zurueckzusenden und anschliessend die Mitteilung mit allen Anhaengen sowie allfaellige Kopien zu vernichten bzw. zu loeschen. Der Gebrauch der Information ist verboten. This message is intended only for the named recipient and may contain confidential or privileged information. If you have received it in error, please advise the sender by return e-mail and delete this message and any attachments. Any unauthorised use or dissemination of this information is strictly prohibited. _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave at boost-consulting.com Thu Nov 23 22:45:17 2006 From: dave at boost-consulting.com (David Abrahams) Date: Thu, 23 Nov 2006 16:45:17 -0500 Subject: [C++-sig] from_python non-compiletime-constant References: Message-ID: <87mz6hg7ma.fsf@pereiro.luannocracy.com> Neal Becker writes: > I need to register a from_python conversion where the type object is not a > compile constant. I'm trying to write c++ code that will accept a numpy > array. > > AFAICT, the PyTypeObject addresses aren't known at compile time, so can't be > used in lvalue_from_pytype template arguments. These pointers can be found > at runtime. How do I handle this? Just take apart the implementation of lvalue_from_pytype and you'll find lower-level facilities in use that will let you build a similar converter. Unfortunately the code for lvalue_from_pytype is pretty convoluted but I've posted the solution several times before on this list so you should be able to find it. -- Dave Abrahams Boost Consulting www.boost-consulting.com From dave at boost-consulting.com Thu Nov 23 22:49:20 2006 From: dave at boost-consulting.com (David Abrahams) Date: Thu, 23 Nov 2006 16:49:20 -0500 Subject: [C++-sig] Crash during exception translation using Intel Compiler 9.1 and optimized builds References: <45636F2E.7090700@innobec.com> Message-ID: <87hcwpg7fj.fsf@pereiro.luannocracy.com> Pierre Baillargeon writes: > We're using the framework to translate C++ exception to Python > exceptions. The code works in debug builds but crashes in optimized > builds. Were using Intel Compiler 9.1 on Windows. > > Has anyone experienced this? > > Any possible workaround? > > The symptoms are: > > - a crash under _is_exception() in MSVCR80.DLL, called from > handle_exception_impl(). Almost certainly a compiler bug unless your own code is corrupting memory and/or code. > - The bottom of the stack is obviously bad: below _is_exception_typeof() > we find tanhf (float's hyperbolic tangent? Microsoft obviously found a > new type-system theorem involving high-level maths), then a long boost > template and 0x0. > - The arguments received in the long boost::python type (which I cannot > see because the name is too long for windbg) are a0, a1 and f, and f is > 0 (which might explain to jump to 0x0). > > Currently the only work-around we've found is to disable the exception > translation. From the look of the stack, it seems that the problem is in > the linked list of translators. Could it be an order-of-initialization > issue? Or a temporary value that should stick around or that the > compiler mistakenly optimizes away? Could be almost anything. Are you trying to run python code at C++'s static initialization time? If so, I could imagine an order-of-initialization issue. If not, not. -- Dave Abrahams Boost Consulting www.boost-consulting.com From dave at boost-consulting.com Thu Nov 23 22:51:42 2006 From: dave at boost-consulting.com (David Abrahams) Date: Thu, 23 Nov 2006 16:51:42 -0500 Subject: [C++-sig] [Boost.Python] shared_ptr References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> <456184CC.8090208@the-mill.com> <456190E4.8050304@the-mill.com> <7465b6170611200329h73a04cdfsc5cd2fae09082e7f@mail.gmail.com> <45619472.5090600@the-mill.com> <7465b6170611201229w3648c1e1ubeb766895ac412e2@mail.gmail.com> Message-ID: <87bqmxg7bl.fsf@pereiro.luannocracy.com> "Roman Yakovenko" writes: > On 11/20/06, Charles Fl?che wrote: >> >> > I think you should also register implicit conversion between smart pointers >> > http://boost.org/libs/python/doc/v2/implicit.html#implicitly_convertible-spec >> >> >> Thank you a lot Kirill and Roman, it's working well now ! > > I just created and tested a complete solution to the problem: > http://pygccxml.svn.sourceforge.net/viewvc/pygccxml/pyplusplus_dev/docs/bpl_lessons_learned/shared_ptr/solution.cpp?view=markup > http://pygccxml.svn.sourceforge.net/viewvc/pygccxml/pyplusplus_dev/docs/bpl_lessons_learned/shared_ptr/test.py?view=markup > > Hope this will be helpful for other too. Hi Roman, Thanks for giving people a stopgap solution. Your overload of get_pointer is clever but unfortunately evil. How about submitting a patch to Boost.Python that actually fixes the problem? -- Dave Abrahams Boost Consulting www.boost-consulting.com From pbaillargeon at innobec.com Fri Nov 24 19:20:23 2006 From: pbaillargeon at innobec.com (Pierre) Date: Fri, 24 Nov 2006 18:20:23 +0000 (UTC) Subject: [C++-sig] =?utf-8?q?Crash_during_exception_translation_using_Inte?= =?utf-8?q?l=09Compiler_9=2E1_and_optimized_builds?= References: <45636F2E.7090700@innobec.com> <87hcwpg7fj.fsf@pereiro.luannocracy.com> Message-ID: David Abrahams boost-consulting.com> writes: > > Pierre Baillargeon innobec.com> writes: > > > We're using the framework to translate C++ exception to Python > > exceptions. The code works in debug builds but crashes in optimized > > builds. Were using Intel Compiler 9.1 on Windows. > > > > Has anyone experienced this? > > > > Any possible workaround? > > > > The symptoms are: > > > > - a crash under _is_exception() in MSVCR80.DLL, called from > > handle_exception_impl(). > > Almost certainly a compiler bug unless your own code is corrupting > memory and/or code. Indeed, I found by trial and error that reducing the aggressiveness of inlining fixed the problem. By switching from "inline whatever the compiler wants" to "inline only function specified as inline" it fixed the problem. We are also using explicit template instantiation, but I do not know if it is a factor in triggering the problem. (We also had problem with compiling 64-bits debug version of boost.python: when we did the std::string converter stopped working, but we didn't investigate that part. Especially since we use version 1.32 of boost and had to work quite a bit to get BJam to compile in 64-bits with that release. But that's another story.) From roman.yakovenko at gmail.com Fri Nov 24 22:02:25 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Fri, 24 Nov 2006 23:02:25 +0200 Subject: [C++-sig] [Boost.Python] shared_ptr In-Reply-To: <87bqmxg7bl.fsf@pereiro.luannocracy.com> References: <455DDD2C.7000409@the-mill.com> <456181E5.8060005@the-mill.com> <45618428.8050904@lapshin.net> <456184CC.8090208@the-mill.com> <456190E4.8050304@the-mill.com> <7465b6170611200329h73a04cdfsc5cd2fae09082e7f@mail.gmail.com> <45619472.5090600@the-mill.com> <7465b6170611201229w3648c1e1ubeb766895ac412e2@mail.gmail.com> <87bqmxg7bl.fsf@pereiro.luannocracy.com> Message-ID: <7465b6170611241302g386df5a9o72c5213e9c37f6d7@mail.gmail.com> On 11/23/06, David Abrahams wrote: > Your overload of get_pointer is clever but unfortunately evil. Yes I know. >How about submitting a > patch to Boost.Python that actually fixes the problem? I will try, but I am not sure I understand the scope of the problem/solution. It is pretty easy to fix the pointer_holder::holds and pointer_holder_back_reference::holds member functions. I did that and the patch is attached. Is this is all that should be done? -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- A non-text attachment was scrubbed... Name: pointer_holder.hpp.patch Type: text/x-patch Size: 3034 bytes Desc: not available URL: From anderslanglands at gmail.com Sat Nov 25 17:19:43 2006 From: anderslanglands at gmail.com (anders langlands) Date: Sat, 25 Nov 2006 16:19:43 +0000 Subject: [C++-sig] need 16 arguments to a function... Message-ID: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> Can I change the max arguments limit for methods without recompiling boost::python? I need an initializer for a 4x4 matrix, hence the need for 16 floats. A -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Sat Nov 25 17:26:13 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sat, 25 Nov 2006 11:26:13 -0500 Subject: [C++-sig] need 16 arguments to a function... In-Reply-To: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> References: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> Message-ID: <45686EA5.7000000@sympatico.ca> anders langlands wrote: > Can I change the max arguments limit for methods without recompiling > boost::python? I need an initializer for a 4x4 matrix, hence the need > for 16 floats. FWIW, I have used hand-coded construction / conversion code to generate C++ containers ('Vector', here) from python lists, such as this: std::auto_ptr construct_vector(bpl::list l) { long len = bpl::extract(l.attr("__len__")()); std::auto_ptr vector(new Vector(len)); for (long i = 0; i != len; ++i) vector->put(i, bpl::extract(l[i])); return vector; } May be something similar would work for you, too ? HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From anderslanglands at gmail.com Sat Nov 25 17:48:31 2006 From: anderslanglands at gmail.com (anders langlands) Date: Sat, 25 Nov 2006 16:48:31 +0000 Subject: [C++-sig] need 16 arguments to a function... In-Reply-To: <45686EA5.7000000@sympatico.ca> References: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> <45686EA5.7000000@sympatico.ca> Message-ID: <57ffdb9c0611250848k288c1d66ra185087f61bb406@mail.gmail.com> Aha yes that's much better, thank you A On 11/25/06, Stefan Seefeld wrote: > > anders langlands wrote: > > Can I change the max arguments limit for methods without recompiling > > boost::python? I need an initializer for a 4x4 matrix, hence the need > > for 16 floats. > > FWIW, I have used hand-coded construction / conversion code to generate > C++ containers ('Vector', here) from python lists, such as this: > > std::auto_ptr construct_vector(bpl::list l) > { > long len = bpl::extract(l.attr("__len__")()); > std::auto_ptr vector(new Vector(len)); > for (long i = 0; i != len; ++i) vector->put(i, > bpl::extract(l[i])); > return vector; > } > > May be something similar would work for you, too ? > > HTH, > Stefan > > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anderslanglands at gmail.com Sat Nov 25 18:31:07 2006 From: anderslanglands at gmail.com (anders langlands) Date: Sat, 25 Nov 2006 17:31:07 +0000 Subject: [C++-sig] need 16 arguments to a function... In-Reply-To: <57ffdb9c0611250848k288c1d66ra185087f61bb406@mail.gmail.com> References: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> <45686EA5.7000000@sympatico.ca> <57ffdb9c0611250848k288c1d66ra185087f61bb406@mail.gmail.com> Message-ID: <57ffdb9c0611250931p28cf28a5m830c942be47f3d37@mail.gmail.com> Hmmm OK now I actually try and use it, it crashes. This is very strange. I'm using almost exactly the same code in another part of my module for getting values back from a list. The code looks like this: M44f m44f_new( list ls ) { size_t len = boost::python::extract( ls.attr( "__len__" )() ); M44f m; cerr << "Length is " << len << endl; for ( int i=0; i < len; ++i ) { cerr << "getting item " << i << endl; boost::python::object x = ls[i]; boost::python::extract ex( x ); if ( ex.check() ) { *(m[ i ]) = ex(); } } return m; } and the output and gdb backtrace looks like this: Length is 16 getting item 0 getting item 1 getting item 2 getting item 3 getting item 4 getting item 5 Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1210632528 (LWP 5042)] 0xb7cb33a5 in boost::python::incref<_object> (p=0x0) at /usr/include/boost/python/refcount.hpp:16 16 Py_INCREF(python::upcast(p)); Current language: auto; currently c++ (gdb) bt #0 0xb7cb33a5 in boost::python::incref<_object> (p=0x0) at /usr/include/boost/python/refcount.hpp:16 #1 0xb7ab1762 in object_base (this=0xbf82dfa8, rhs=@0xbf82e03c) at /usr/include/boost/python/object_core.hpp:419 #2 0xb7ab1794 in object (this=0xbf82dfa8) at /usr/include/boost/python/object_core.hpp:294 #3 0xb7ab7e73 in proxy (this=0xbf82dfa8, target=@0xbf82e03c, key=@0xbf82df08) at /usr/include/boost/python/proxy.hpp:58 #4 0xb7ab7ec2 in boost::python::api::object_operators::operator[] (this=0xbf82e03c, key=@0xbf82df08) at /usr/include/boost/python/object_items.hpp:36 #5 0xb7ab93d1 in boost::python::api::object_operators::operator[] (this=0xbf82e03c, key=@0xbf82dfb4) at /usr/include/boost/python/object_items.hpp:61 #6 0xb7ac872a in PymathBinding::m44f_new (ls=@0xbf82e03c) at src/Pymath.cpp:89 #7 0xb7ae460c in boost::python::detail::invoke const&>, Imath::Matrix44 (*)(boost::python::list), boost::python::arg_from_python > (rc=@0xbf82e07e, f=@0x817f794, ac0=@0xbf82e070) at /usr/include/boost/python/detail/invoke.hpp:75 #8 0xb7ae49bf in boost::python::detail::caller_arity<1u>::impl (*)(boost::python::list), boost::python::default_call_policies, boost::mpl::vector2, boost::python::list> >::operator() ( ---Type to continue, or q to quit--- this=0x817f794, args_=0xb7d0180c) at /usr/include/boost/python/detail/caller.hpp:199 #9 0xb7ae4a1a in boost::python::objects::caller_py_function_impl (*)(boost::python::list), boost::python::default_call_policies, boost::mpl::vector2, boost::python::list> > >::operator() (this=0x817f790, args=0xb7d0180c, kw=0x0) at /usr/include/boost/python/object/py_function.hpp:38 #10 0xb7bbc6d6 in boost::python::objects::function::call () from /usr/lib/libboost_python-gcc-mt-1_33_1.so.1.33.1 #11 0x0817f790 in ?? () #12 0xb7d0180c in ?? () #13 0x00000000 in ?? () I'm calling it like this in the python script: xform = newM44f( [ 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 7.367355, 1.000000, ] ) Any ideas what could be happening? A On 11/25/06, anders langlands wrote: > > Aha yes that's much better, thank you > > A > > On 11/25/06, Stefan Seefeld wrote: > > > > anders langlands wrote: > > > Can I change the max arguments limit for methods without recompiling > > > boost::python? I need an initializer for a 4x4 matrix, hence the need > > > for 16 floats. > > > > FWIW, I have used hand-coded construction / conversion code to generate > > C++ containers ('Vector', here) from python lists, such as this: > > > > std::auto_ptr construct_vector(bpl::list l) > > { > > long len = bpl::extract(l.attr("__len__")()); > > std::auto_ptr vector(new Vector(len)); > > for (long i = 0; i != len; ++i) vector->put(i, > > bpl::extract(l[i])); > > return vector; > > } > > > > May be something similar would work for you, too ? > > > > HTH, > > Stefan > > > > > > -- > > > > ...ich hab' noch einen Koffer in Berlin... > > _______________________________________________ > > C++-sig mailing list > > C++-sig at python.org > > http://mail.python.org/mailman/listinfo/c++-sig > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Sat Nov 25 19:06:22 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sat, 25 Nov 2006 13:06:22 -0500 Subject: [C++-sig] need 16 arguments to a function... In-Reply-To: <57ffdb9c0611250931p28cf28a5m830c942be47f3d37@mail.gmail.com> References: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> <45686EA5.7000000@sympatico.ca> <57ffdb9c0611250848k288c1d66ra185087f61bb406@mail.gmail.com> <57ffdb9c0611250931p28cf28a5m830c942be47f3d37@mail.gmail.com> Message-ID: <4568861E.4000104@sympatico.ca> anders langlands wrote: > Hmmm OK now I actually try and use it, it crashes. This is very strange. > I'm using almost exactly the same code in another part of my module for > getting values back from a list. No idea. Is this a multi-threaded program ? Do other parts access the 'ls' list at the same time ? In that case you ought to serialize access by means of the global interpreter lock (GIL). Otherwise I have no clue, sorry. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From anderslanglands at gmail.com Sat Nov 25 19:14:50 2006 From: anderslanglands at gmail.com (anders langlands) Date: Sat, 25 Nov 2006 18:14:50 +0000 Subject: [C++-sig] need 16 arguments to a function... In-Reply-To: <4568861E.4000104@sympatico.ca> References: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> <45686EA5.7000000@sympatico.ca> <57ffdb9c0611250848k288c1d66ra185087f61bb406@mail.gmail.com> <57ffdb9c0611250931p28cf28a5m830c942be47f3d37@mail.gmail.com> <4568861E.4000104@sympatico.ca> Message-ID: <57ffdb9c0611251014u2ac0c28fo92c30fcea0762f47@mail.gmail.com> Sorry, don't mind me. I was trying to write into the matrix object the wrong way and i guess it was corrupting the stack :) Thanks for your help stefan A On 11/25/06, Stefan Seefeld wrote: > > anders langlands wrote: > > Hmmm OK now I actually try and use it, it crashes. This is very strange. > > I'm using almost exactly the same code in another part of my module for > > getting values back from a list. > > No idea. Is this a multi-threaded program ? Do other parts access the 'ls' > list at the same time ? In that case you ought to serialize access by > means > of the global interpreter lock (GIL). > Otherwise I have no clue, sorry. > > Regards, > Stefan > > > > -- > > ...ich hab' noch einen Koffer in Berlin... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Sat Nov 25 19:49:38 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Sat, 25 Nov 2006 20:49:38 +0200 Subject: [C++-sig] need 16 arguments to a function... In-Reply-To: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> References: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> Message-ID: <7465b6170611251049l3c81fa5ka8e24d6e8c4495c6@mail.gmail.com> On 11/25/06, anders langlands wrote: > Can I change the max arguments limit for methods without recompiling > boost::python? I need an initializer for a 4x4 matrix, hence the need for 16 > floats. Take a look on this mail. http://mail.python.org/pipermail/c++-sig/2002-June/001554.html I think, you don't need to re-compile boost.python, but your projects. ( But of course I could be wrong ) -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From lars.yencken at gmail.com Sun Nov 26 04:29:50 2006 From: lars.yencken at gmail.com (Lars Yencken) Date: Sun, 26 Nov 2006 12:29:50 +0900 Subject: [C++-sig] Boost python in OS X, with non-framework python 2.4 Message-ID: Hello! [apologies for long post ahead] I've been using boost python with some of my research code for a little while on linux, and have really enjoyed it. I've been having trouble on my new mac laptop though, since (a) I have a large codebase that needs python2.4, and (b) I can't seem to compile and link boost python extensions against python2.4 as provided by fink or darwin ports. No matter what I try, I can only get extensions successfully compiled for the framework python2.3 which comes with OS X. I know this because with python 2.4 (from fink) my code gives Fatal Python error: Interpreter not initialized (version mismatch?) Abort trap whereas this doesn't occur with 2.3, where the extension works fine. If I use boost.python from fink or darwin ports, the problem is the same. I've tried installing my own version, using configure arguments --with-python=/sw/bin/python2.4 --with-python-root=/sw --with-python-version=2.4 --with-libraries=python. Here's the output from the previous compilation stage for my extension, which appears to be successful: g++ -o dataType.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost dataType.cpp g++ -o entry.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost entry.cpp g++ -o alignment.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost alignment.cpp g++ -o ambiguousAlignment.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost ambiguousAlignment.cpp g++ -o utils.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost utils.cpp g++ -o dataType.dylib -dylib -bundle -L/sw/lib -lpython2.4 -lboost_python -lm dataType.o entry.o alignment.o ambiguousAlignment.o utils.o I did see some earlier posts on this, but they seemed a bit unresolved. From my understanding, regardless of command line options you give to configure, if you compile boost.python using the darwin toolset, it links against the framework python. I tried building using the gcc toolset, and specifying --with-python=/sw/bin/python2.4 --with-python-root=/sw --with-python-version=2.4 --with-libraries=python. If you do this, the g++ arguments are actually wrong for OS X, and you have to manually perform the final linking step yourself. This works, if you change c++ -s -fPIC -shared -o to c++ -dynamiclib -dynamic -o -L/sw/lib -lpython2.4 for the targets libboost_python-gcc-1_33_1.dylib and libboost_python-gcc-d-1_33_1.dylib (leaving in the -g flag for the debug library). I can then install it. After all this, I try recompiling. g++ -o dataType.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost dataType.cpp g++ -o entry.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost entry.cpp g++ -o alignment.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost alignment.cpp g++ -o ambiguousAlignment.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost ambiguousAlignment.cpp g++ -o utils.o -c -Wall -O3 -fPIC -I/sw/include/python2.4 -I/usr/local/include/boost utils.cpp g++ -o dataType.so -dylib -bundle -L/sw/lib -lpython2.4 -lboost_python-gcc-1_33_1 -lm dataType.o entry.o alignment.o ambiguousAlignment.o utils.o Now, when I test, I get same error, but with python2.3, python2.4 and python2.5. This to me indicates that either my library, or boost's library, has been compiled with a mixture of python flavours, acceptable to none. Does anyone have any ideas on what else I could try, or suggestions in the case I'm barking up the wrong tree? Many thanks, Lars From rwgk at yahoo.com Sun Nov 26 07:34:25 2006 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sat, 25 Nov 2006 22:34:25 -0800 (PST) Subject: [C++-sig] Boost python in OS X, with non-framework python 2.4 Message-ID: <20061126063425.60219.qmail@web31109.mail.mud.yahoo.com> I successfully built a large set of Boost.Python extensions under Mac OS 10.4 Intel with Python 2.3, 2.4, and 2.5, and under Mac OS 10.3 PPC with Python 2.3 and 2.5 (I bet 2.4 will also work, but I didn't try). I only managed to build successfully against Python frameworks. I don't know if it is possible to work with a normal/plain Python build as you get e.g. from fink. You can install a Python framework from sources like this: ./configure --enable-framework make make frameworkinstall For the last step you'll need to be root. The installation will go to "/Library/Frameworks/Python.Framework/Versions/2.?/" and "/Applications/MacPython 2.?", and you'll get a new set of softlinks in /usr/local. I'm using a scons-based build system, therefore I don't know how to convince bjam to use the Python installation you want. Hopefully someone else can help out. ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com From lars.yencken at gmail.com Sun Nov 26 12:06:48 2006 From: lars.yencken at gmail.com (Lars Yencken) Date: Sun, 26 Nov 2006 20:06:48 +0900 Subject: [C++-sig] Boost python in OS X, with non-framework python 2.4 In-Reply-To: <20061126063425.60219.qmail@web31109.mail.mud.yahoo.com> References: <20061126063425.60219.qmail@web31109.mail.mud.yahoo.com> Message-ID: Hi Ralf, Thanks for the suggestion. Maybe I've been going about this the wrong way. I installed the OS X package for python 2.5. I then had a go at compiling boost python against framework python 2.5 (the one symlinked to current) on intel, but had compile errors. Every one was of the form: /Users/lars/Downloads/Work/boost_1_33_1/libs/python/build/../src/ object_protocol.cpp:139: error: invalid conversion from 'int*' to 'Py_ssize_t*' My guess is that part of the python interface changed between versions (this one type/typedef of Py_ssize_t?). I imagine that using a more recent dev version of boost python might get around this, so that's what I'll try now. It's comforting that you've been successful though. You wouldn't believe how much time I've spent trying to get this working. Lars From dave at boost-consulting.com Sun Nov 26 16:15:08 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 26 Nov 2006 10:15:08 -0500 Subject: [C++-sig] Crash during exception translation using Intel Compiler 9.1 and optimized builds References: <45636F2E.7090700@innobec.com> <87hcwpg7fj.fsf@pereiro.luannocracy.com> Message-ID: <87bqmu9r43.fsf@pereiro.luannocracy.com> Pierre writes: > David Abrahams boost-consulting.com> writes: > >> >> Pierre Baillargeon innobec.com> writes: >> >> > We're using the framework to translate C++ exception to Python >> > exceptions. The code works in debug builds but crashes in optimized >> > builds. Were using Intel Compiler 9.1 on Windows. >> > >> > Has anyone experienced this? >> > >> > Any possible workaround? >> > >> > The symptoms are: >> > >> > - a crash under _is_exception() in MSVCR80.DLL, called from >> > handle_exception_impl(). >> >> Almost certainly a compiler bug unless your own code is corrupting >> memory and/or code. > > Indeed, I found by trial and error that reducing the aggressiveness of inlining > fixed the problem. By switching from "inline whatever the compiler wants" to > "inline only function specified as inline" it fixed the problem. I hope you can make a report to Intel and get them to fix the bug. -- Dave Abrahams Boost Consulting www.boost-consulting.com From lars.yencken at gmail.com Sun Nov 26 16:21:39 2006 From: lars.yencken at gmail.com (Lars Yencken) Date: Mon, 27 Nov 2006 00:21:39 +0900 Subject: [C++-sig] Boost python in OS X, with non-framework python 2.4 In-Reply-To: <20061126063425.60219.qmail@web31109.mail.mud.yahoo.com> References: <20061126063425.60219.qmail@web31109.mail.mud.yahoo.com> Message-ID: <9732006E-55C0-4C2B-98AA-0915203A540F@gmail.com> Ok, after some trouble, someone mentioned the command otool, and using otool -L I was able to debug some of my strange shared library problems, some of which were undoubtedly caused by trying too hard (many versions of python, many simultaneous installs of boost.python, frameworks, fink, darwinports...). I removed all the alternative versions of python and boost python, fully deleted the current install of boost python, and reinstalled it for framework python 2.4. I can now successfully build extensions on python 2.4, so I'm happy. Thanks for the help! Lars On 26/11/2006, at 3:34 PM, Ralf W. Grosse-Kunstleve wrote: > I successfully built a large set of Boost.Python extensions under Mac > OS 10.4 Intel with Python 2.3, 2.4, and 2.5, and under Mac OS 10.3 PPC > with Python 2.3 and 2.5 (I bet 2.4 will also work, but I didn't try). > > I only managed to build successfully against Python frameworks. I > don't know if it is possible to work with a normal/plain Python build > as you get e.g. from fink. > > You can install a Python framework from sources like this: > > ./configure --enable-framework > make > make frameworkinstall > > For the last step you'll need to be root. The installation will go to > "/Library/Frameworks/Python.Framework/Versions/2.?/" and > "/Applications/MacPython 2.?", and you'll get a new set of > softlinks in > /usr/local. > > I'm using a scons-based build system, therefore I don't know how to > convince bjam to use the Python installation you want. Hopefully > someone else can help out. > > > > > > > ______________________________________________________________________ > ______________ > Do you Yahoo!? > Everyone is raving about the all-new Yahoo! Mail beta. > http://new.mail.yahoo.com > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig From dave at boost-consulting.com Sun Nov 26 16:22:24 2006 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 26 Nov 2006 10:22:24 -0500 Subject: [C++-sig] need 16 arguments to a function... References: <57ffdb9c0611250819u4a60b19bof88aa901bd6af17b@mail.gmail.com> Message-ID: <8764d29qrz.fsf@pereiro.luannocracy.com> "anders langlands" writes: > Can I change the max arguments limit for methods without recompiling boost::python? I need an > initializer for a 4x4 matrix, hence the need for 16 floats. http://www.boost.org/libs/python/doc/v2/configuration.html should tell you what you need to know. -- Dave Abrahams Boost Consulting www.boost-consulting.com From rwgk at yahoo.com Sun Nov 26 18:51:40 2006 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sun, 26 Nov 2006 09:51:40 -0800 (PST) Subject: [C++-sig] Boost python in OS X, with non-framework python 2.4 Message-ID: <20061126175140.1322.qmail@web31110.mail.mud.yahoo.com> > From: Lars Yencken > > My guess is that part of the python interface changed between > versions (this one type/typedef of Py_ssize_t?). I imagine that using > a more recent dev version of boost python might get around this, Yes, exactly. The current boost cvs HEAD should work with any Python >= 2.2. I tried the HEAD successfully the day before yesterday, with a whole bunch of compilers. Cheers, Ralf ____________________________________________________________________________________ Yahoo! Music Unlimited Access over 1 million songs. http://music.yahoo.com/unlimited From shashankbapat at hotmail.com Mon Nov 27 00:02:00 2006 From: shashankbapat at hotmail.com (Shashank Bapat) Date: Sun, 26 Nov 2006 18:02:00 -0500 Subject: [C++-sig] enum pickle issue in boost python Message-ID: Both pickle and cPickle seem to have problem pickling boost wrapped enum types. Pickle protocol used here is 2. Problem is causes by enum.cpp. In there __name__ and __module__ are intentionally set in certain way (which is different than how its done in class.cpp). So I suppose there is a valid reason why its that way. In that case the __reduce__ and __reduce_ex__ implementation for enum_ should take care of this so as to ensure proper pickling. Example: import EnumTest import cPickle try: print "Lets pickle some boost enum:" f = open("tmp1.txt", "w") cPickle.dump( EnumTest.Color.red , f, cPickle.HIGHEST_PROTOCOL) except: print "FAIL\n" try: print "Why is EnumTest.Color.__name__ = '%s' and \nEnumTest.Color.__module__= '%s' ?\n" % ( EnumTest.Color.__name__, EnumTest.Color.__module__) print "Lets hack it and try again:" f = open("tmp2.txt", "w") EnumTest.Color.__name__ = "Color" EnumTest.Color.__module__ = "EnumTest" l = (EnumTest.Color.red, EnumTest.Color.green, EnumTest.Color.blue) for e in l: cPickle.dump( e , f, cPickle.HIGHEST_PROTOCOL) f.close() print "PASS\n" print "Unpickle Test:" f = open("tmp2.txt", "r") for e in l: if e != cPickle.load(f): raise "Load Failed" print "PASS\n" except: print "FAIL\n" Thanks -Shashank _________________________________________________________________ View Athlete?s Collections with Live Search http://sportmaps.live.com/index.html?source=hmemailtaglinenov06&FORM=MGAC01 From rwgk at yahoo.com Mon Nov 27 01:30:57 2006 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Sun, 26 Nov 2006 16:30:57 -0800 (PST) Subject: [C++-sig] enum pickle issue in boost python Message-ID: <20061127003057.14652.qmail@web31110.mail.mud.yahoo.com> What is the EnumTest? Are you aware of this page? http://www.boost.org/libs/python/doc/v2/pickle.html I wrote the Boost.Python pickle support, but I never tried it with enum types. If you think Boost.Python needs tweaking, could you please work with the cvs HEAD, if you don't already? ----- Original Message ---- From: Shashank Bapat To: c++-sig at python.org Sent: Sunday, November 26, 2006 3:02:00 PM Subject: [C++-sig] enum pickle issue in boost python Both pickle and cPickle seem to have problem pickling boost wrapped enum types. Pickle protocol used here is 2. Problem is causes by enum.cpp. In there __name__ and __module__ are intentionally set in certain way (which is different than how its done in class.cpp). So I suppose there is a valid reason why its that way. In that case the __reduce__ and __reduce_ex__ implementation for enum_ should take care of this so as to ensure proper pickling. Example: import EnumTest import cPickle try: print "Lets pickle some boost enum:" f = open("tmp1.txt", "w") cPickle.dump( EnumTest.Color.red , f, cPickle.HIGHEST_PROTOCOL) except: print "FAIL\n" try: print "Why is EnumTest.Color.__name__ = '%s' and \nEnumTest.Color.__module__= '%s' ?\n" % ( EnumTest.Color.__name__, EnumTest.Color.__module__) print "Lets hack it and try again:" f = open("tmp2.txt", "w") EnumTest.Color.__name__ = "Color" EnumTest.Color.__module__ = "EnumTest" l = (EnumTest.Color.red, EnumTest.Color.green, EnumTest.Color.blue) for e in l: cPickle.dump( e , f, cPickle.HIGHEST_PROTOCOL) f.close() print "PASS\n" print "Unpickle Test:" f = open("tmp2.txt", "r") for e in l: if e != cPickle.load(f): raise "Load Failed" print "PASS\n" except: print "FAIL\n" Thanks -Shashank ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com From shashankbapat at hotmail.com Mon Nov 27 23:46:37 2006 From: shashankbapat at hotmail.com (Shashank Bapat) Date: Mon, 27 Nov 2006 17:46:37 -0500 Subject: [C++-sig] enum pickle issue in boost python Message-ID: Ralf, Yes. I am aware of the boost pickle tutorial. It is useful if I have some complicated pickle logic in a class. But if you see enum_ has reduce and reduce_ex already defined in that case I shouldnt need to do anything special to get my enum pickled. ie providing additional methods for each enum_ to ensure correct pickling seems unnecessry. EnumTest is boost wrapper around an enum. Something like: namespace { enum Color { red = 1, green = 2, blue = 4 }; } BOOST_PYTHON_MODULE( EnumTest ) { boost::python::scope().attr("__doc__") = "Module to test Boost Python enums"; boost::python::enum_( "Color" ) .value( "red", red ) .value( "green", green ) .value( "blue", blue ) .export_values() ; } Check how class.cpp is differnt from enum.cpp in a way it processes module and name. I can fix it myself but I was wondering why is enum_ doing things differntly. May be this is just a mistake but may be there is a good reason. In that case I ll fix it and it will break something else somewhere ! Any case I ll try cvs HEAD and let you know. -Shashank _________________________________________________________________ Stay up-to-date with your friends through the Windows Live Spaces friends list. http://clk.atdmt.com/MSN/go/msnnkwsp0070000001msn/direct/01/?href=http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mk From kelly.burkhart at gmail.com Tue Nov 28 00:14:03 2006 From: kelly.burkhart at gmail.com (Kelly Burkhart) Date: Mon, 27 Nov 2006 17:14:03 -0600 Subject: [C++-sig] compile error in iterator Message-ID: I have a GzipFile class which exposes a gzipped file as a python file. I have written an iterator over this class which I use to iterate over an instance of this class. I'm using 1.33.1 and my code compiles cleanly and works on Linux g++ 3.3.5. I am now trying to build on Windows using msvc.net (cl 13.10.6030). This compiler complains that bost::python::objects::iterator_range::next is not accessible (full compiler complaint below). Does anyone have a solution, or hint to how I can go about fixing this? Thank you in advance for any assistance. This code reproduces the problem: #include #include #include #include using namespace boost::python; //-------------------------------------------------------------------------------------------------- // class ItTstIterator : public boost::iterator_facade< ItTstIterator, std::string, boost::forward_traversal_tag, std::string > { public: ItTstIterator( std::vector::iterator it ) : it_(it) {} virtual ~ItTstIterator() {} private: friend class boost::iterator_core_access; void increment() { ++it_; } bool equal( const ItTstIterator &it ) const { return it_ == it.it_; } std::string dereference() const { return *it_; } private: std::vector::iterator it_; }; //-------------------------------------------------------------------------------------------------- class ItTst { public: typedef ItTstIterator iterator; ItTst() { vec_.push_back("one");vec_.push_back("two");vec_.push_back("three"); } ~ItTst() {} // For iteration ItTstIterator begin() { return ItTstIterator( vec_.begin() ); } ItTstIterator end() { return ItTstIterator( vec_.end() ); } private: std::vector< std::string > vec_; }; void wrapPyIter() { class_("ItTst", init<>() ) .def("__iter__", iterator()) ; } And here is the full compiler complaint: cl -c -nologo -GX -GR -Zc:forScope -wd4101 -wd4290 -wd4100 -wd4189 -DWIN32 -Zi -Od -D_DEBUG -DFD_SETSIZE=512 -MDd -Zi -Od -D_DEBUG -DFD_SETSIZE=512 -MDd -DBOOST_SIGNALS_NAMESPACE=tb_signals -D__x86__ -D__NT__ -D__OSVERSION__=5 -D__WIN32__ -GR -EHsc -W3 -w34100 -w34189 -DWIN32 -DQT_LARGEFILE_SUPPORT -DCOMPILE_DL=1 -DQT_DLL -DQT_PLUGIN -DQT_QT3SUPPORT_LIB -DQT3_SUPPORT -DQT_XML_LIB -DQT_GUI_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT -D_WIN32_WINNT=0x0500 -DFD_SETSIZE=512 -DNOMINMAX -I"C:/Qt/4.2.1/include/QtCore" -I"C:/Qt/4.2.1/include/QtCore" -I"C:/Qt/4.2.1/include/QtNetwork" -I"C:/Qt/4.2.1/include/QtNetwork" -I"C:/Qt/4.2.1/include/QtGui" -I"C:/Qt/4.2.1/include/QtGui" -I"C:/Qt/4.2.1/include/QtXml" -I"C:/Qt/4.2.1/include/QtXml" -I"C:/Qt/4.2.1/include/Qt3Support" -I"C:/Qt/4.2.1/include/Qt3Support" -I"C:/Qt/4.2.1/include" -I"..\Common" -I"..\libtbut" -I"C:/Qt/4.2.1/include/ActiveQt" -I"moc" -I"..\libtbut" -I"ui" -I"C:/postgresql\src\interfaces\libpq" -I"C:/postgresql\src\include" -I"C:/Python25/include" -I"C:/Boost/include/boost-1_33_1" -I"c:\omni\omniORB-4.0.3\include" -I"c:\Qt\4.2.1\mkspecs\win32-msvc.net" -Fodebug\ @c:\DOCUME~1\kelly\LOCALS~1\Temp\nm99.tmp wrap_py_iter.cpp C:/Boost\include\boost-1_33_1\boost\detail\compressed_pair.hpp(347) : error C2247: 'boost::python::objects::iterator_range::next' not accessible because 'boost::details::compressed_pair_imp' uses 'private' to inherit from 'boost::python::objects::iterator_range::next' with [ NextPolicies=boost::python::return_value_policy, Iterator=iterator_const ] and [ T1=boost::python::objects::iterator_range,iterator_const>::next, T2=boost::python::return_value_policy, Version=3 ] and [ NextPolicies=boost::python::return_value_policy, Iterator=iterator_const ] C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(51) : see declaration of 'boost::python::objects::iterator_range::next' with [ NextPolicies=boost::python::return_value_policy, Iterator=iterator_const ] C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(51) : see declaration of 'boost::python::objects::iterator_range::next' with [ NextPolicies=boost::python::return_value_policy, Iterator=iterator_const ] C:/Boost\include\boost-1_33_1\boost\python\detail\caller.hpp(212) : see reference to class template instantiation 'boost::compressed_pair' being compiled with [ T1=boost::python::objects::iterator_range,iterator_const>::next, T2=boost::python::return_value_policy ] C:/Boost\include\boost-1_33_1\boost\python\detail\caller.hpp(145) : see reference to class template instantiation 'boost::python::detail::caller_arity<1>::impl' being compiled with [ F=boost::python::objects::iterator_range,iterator_const>::next, Policies=boost::python::return_value_policy, Sig=boost::mpl::vector2 ] C:/Boost\include\boost-1_33_1\boost\python\make_function.hpp(37) : see reference to class template instantiation 'boost::python::detail::caller' being compiled with [ F=boost::python::objects::iterator_range,iterator_const>::next, CallPolicies=boost::python::return_value_policy, Sig=boost::mpl::vector2 ] C:/Boost\include\boost-1_33_1\boost\python\make_function.hpp(89) : see reference to function template instantiation 'boost::python::api::object boost::python::detail::make_function_aux(F,const CallPolicies &,const Sig &)' being compiled with [ F=boost::python::objects::iterator_range,iterator_const>::next, CallPolicies=boost::python::return_value_policy, Signature=boost::mpl::vector2, Sig=boost::mpl::vector2 ] C:/Boost\include\boost-1_33_1\boost\python\make_function.hpp(129) : see reference to function template instantiation 'boost::python::api::object boost::python::detail::make_function_dispatch(F,const CallPolicies &,const Signature &,boost::mpl::false_)' being compiled with [ F=boost::python::objects::iterator_range,iterator_const>::next, CallPolicies=boost::python::return_value_policy, KeywordsOrSignature=boost::mpl::vector2, Signature=boost::mpl::vector2 ] C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(137) : see reference to function template instantiation 'boost::python::api::object boost::python::make_function::next,NextPolicies,boost::mpl::vector2>(F,const CallPolicies &,const KeywordsOrSignature &)' being compiled with [ NextPolicies=boost::python::return_value_policy, Iterator=iterator_const, T0=result_type, T1=range_ &, F=boost::python::objects::iterator_range,iterator_const>::next, CallPolicies=boost::python::return_value_policy, KeywordsOrSignature=boost::mpl::vector2 ] C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(163) : see reference to function template instantiation 'boost::python::api::object boost::python::objects::detail::demand_iterator_class>(const char *,Iterator *,const NextPolicies &)' being compiled with [ Iterator=const iterator_const, ResultConverterGenerator=boost::python::return_by_value, NextPolicies=boost::python::return_value_policy ] C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(161) : while compiling class-template member function 'boost::python::objects::iterator_range boost::python::objects::detail::py_iter_::operator ()(boost::python::back_reference) const' with [ NextPolicies=boost::python::return_value_policy, Iterator=iterator_const, Target=ItTst, Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, T=ItTst & ] C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(187) : see reference to class template instantiation 'boost::python::objects::detail::py_iter_' being compiled with [ Target=ItTst, Iterator=iterator_const, Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, NextPolicies=boost::python::return_value_policy ] C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(239) : see reference to function template instantiation 'boost::python::api::object boost::python::objects::detail::make_iterator_function(const Accessor1 &,const Accessor2 &,const NextPolicies &,Iterator &(__cdecl *)(void),boost::type *,int)' being compiled with [ Target=ItTst, T=const iterator_const, NextPolicies=boost::python::return_value_policy, Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, Iterator=const iterator_const ] C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(39) : see reference to function template instantiation 'boost::python::api::object boost::python::objects::make_iterator_function,boost::_bi::protected_bind_t>(const Accessor1 &,const Accessor2 &,const NextPolicies &,boost::type *)' being compiled with [ Target=ItTst, NextPolicies=boost::python::return_value_policy, F=boost::_bi::bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>, Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &),boost::_bi::list1>::B1>>>, T=ItTst ] C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(96) : see reference to function template instantiation 'boost::python::api::object boost::python::detail::make_iterator::apply::iterator(__cdecl *)(T &),boost::python::detail::iterators_impl::apply::iterator(__cdecl *)(T &),boost::python::return_value_policy>(Accessor1,Accessor2,NextPolicies,Target &(__cdecl *)(void))' being compiled with [ T=ItTst, const_=false, ResultConverterGenerator=boost::python::return_by_value, Accessor1=boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &), Accessor2=boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &), NextPolicies=boost::python::return_value_policy, Target=ItTst ] C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(120) : see reference to function template instantiation 'boost::python::api::object boost::python::range::apply::iterator(__cdecl *)(T &),boost::python::detail::iterators_impl::apply::iterator(__cdecl *)(T &)>(Accessor1,Accessor2,NextPolicies *)' being compiled with [ NextPolicies=boost::python::objects::default_iterator_call_policies, const_=false, T=ItTst, Accessor1=boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &), Accessor2=boost::python::detail::iterators_impl::apply::iterator (__cdecl *)(ItTst &) ] C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(116) : while compiling class-template member function 'boost::python::iterator::iterator(void)' with [ Container=ItTst ] wrap_py_iter.cpp(48) : see reference to class template instantiation 'boost::python::iterator' being compiled with [ Container=ItTst ] NMAKE : fatal error U1077: 'cl' : return code '0x2' Stop. NMAKE : fatal error U1077: '"c:\Program Files\Microsoft Visual Studio .NET 2003\VC7\BIN\nmake.exe"' : return code '0x2' Stop. From shashankbapat at hotmail.com Tue Nov 28 01:55:24 2006 From: shashankbapat at hotmail.com (Shashank Bapat) Date: Mon, 27 Nov 2006 19:55:24 -0500 Subject: [C++-sig] enum pickle issue in boost python Message-ID: Ralf, I tried cvs HEAD and it has same problem. So I fixed it in my local copy (see diff below). This change is equivalent to class.cpp change made in version 1.50 of class.cpp: http://boost.cvs.sourceforge.net/boost/boost/libs/python/src/object/class.cpp?hideattic=0&r1=1.49&r2=1.50 Thanks -Shashank =================================================================== RCS file: /cvsroot/boost/boost/libs/python/src/object/enum.cpp,v retrieving revision 1.9 diff -r1.9 enum.cpp 144c144 < module_name += '.'; --- > d["__module__"] = module_name; 146,147c146 < object result = (object(metatype))( < module_name + name, make_tuple(base), d); --- > object result = (object(metatype))(name, make_tuple(base), d); _________________________________________________________________ Share your latest news with your friends with the Windows Live Spaces friends module. http://clk.atdmt.com/MSN/go/msnnkwsp0070000001msn/direct/01/?href=http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mk From rwgk at yahoo.com Tue Nov 28 02:28:15 2006 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 27 Nov 2006 17:28:15 -0800 (PST) Subject: [C++-sig] enum pickle issue in boost python Message-ID: <20061128012815.7191.qmail@web31114.mail.mud.yahoo.com> Thanks! Could you please also add pickle.dumps, pickle.loads tests to boost/libs/python/test/enum.py? If you could send the patched files (just to me, not the list) I'll test them locally and check them in. ----- Original Message ---- From: Shashank Bapat To: c++-sig at python.org Sent: Monday, November 27, 2006 4:55:24 PM Subject: [C++-sig] enum pickle issue in boost python Ralf, I tried cvs HEAD and it has same problem. So I fixed it in my local copy (see diff below). This change is equivalent to class.cpp change made in version 1.50 of class.cpp: http://boost.cvs.sourceforge.net/boost/boost/libs/python/src/object/class.cpp?hideattic=0&r1=1.49&r2=1.50 Thanks -Shashank =================================================================== RCS file: /cvsroot/boost/boost/libs/python/src/object/enum.cpp,v retrieving revision 1.9 diff -r1.9 enum.cpp 144c144 < module_name += '.'; --- > d["__module__"] = module_name; 146,147c146 < object result = (object(metatype))( < module_name + name, make_tuple(base), d); --- > object result = (object(metatype))(name, make_tuple(base), d); ____________________________________________________________________________________ Cheap talk? Check out Yahoo! Messenger's low PC-to-Phone call rates. http://voice.yahoo.com From bernhard.maeder at zkb.ch Tue Nov 28 11:08:46 2006 From: bernhard.maeder at zkb.ch (bernhard.maeder at zkb.ch) Date: Tue, 28 Nov 2006 11:08:46 +0100 Subject: [C++-sig] Antwort: Re: Wrapping a base class' method In-Reply-To: <20061123173710.14449.qmail@web31115.mail.mud.yahoo.com> Message-ID: > Write a thin wrapper and .add_property that, e.g. (untested) > > int get_base_i_directly(my_class const& self) { return self.get_base_i(); } > ... > .add_property("basei", make_function(get_base_i_directly)) > > This way Boost.Python only "sees" my_class in the signature. Yes, thanks, that works. What puzzles me, is that the same works for return-by-value wrappings. I don't quite get why that's something different to boost.python. Is there an easy explanation or am I just missing the obvious? Thanks Bernhard ___________________________________________________________________ Disclaimer: Diese Mitteilung ist nur fuer die Empfaengerin / den Empfaenger bestimmt. Fuer den Fall, dass sie von nichtberechtigten Personen empfangen wird, bitten wir diese hoeflich, die Mitteilung an die ZKB zurueckzusenden und anschliessend die Mitteilung mit allen Anhaengen sowie allfaellige Kopien zu vernichten bzw. zu loeschen. Der Gebrauch der Information ist verboten. This message is intended only for the named recipient and may contain confidential or privileged information. If you have received it in error, please advise the sender by return e-mail and delete this message and any attachments. Any unauthorised use or dissemination of this information is strictly prohibited. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ext at sidvind.com Tue Nov 28 13:08:55 2006 From: ext at sidvind.com (David Sveningsson) Date: Tue, 28 Nov 2006 13:08:55 +0100 Subject: [C++-sig] Multiple modules in a file Message-ID: <456C26D7.2090206@sidvind.com> Hi, I am quite new at extending python with c++. I am using the boost libraries on gnu/linux. I have many classes (with inheritance) that I would like to expose to python. Is there some way to have many python modules in one file? Like, core.so contains a string class and a memory class. I tried just compiling everything as a shared library and importing into python with "import core.string" but then I get the error "ImportError: dynamic module does not define init function (initcore)" Im not really sure what that means. From roman.yakovenko at gmail.com Tue Nov 28 13:48:59 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 28 Nov 2006 14:48:59 +0200 Subject: [C++-sig] Multiple modules in a file In-Reply-To: <456C26D7.2090206@sidvind.com> References: <456C26D7.2090206@sidvind.com> Message-ID: <7465b6170611280448u4025ccd3q2dd269a0f2c51a70@mail.gmail.com> On 11/28/06, David Sveningsson wrote: > Hi, I am quite new at extending python with c++. I am using the boost > libraries on gnu/linux. I have many classes (with inheritance) that I > would like to expose to python. Is there some way to have many python > modules in one file? I don't think so. I think you can achieve the desired effect using Python API. May be you should take a look on "Creating Packages" tutorial. ( http://boost.org/libs/python/doc/tutorial/doc/html/python/techniques.html#python.creating_packages ) -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From Nicolas.Rougier at loria.fr Tue Nov 28 16:09:41 2006 From: Nicolas.Rougier at loria.fr (Nicolas Rougier) Date: Tue, 28 Nov 2006 16:09:41 +0100 Subject: [C++-sig] Multiple modules in a file In-Reply-To: <456C26D7.2090206@sidvind.com> References: <456C26D7.2090206@sidvind.com> Message-ID: <1164726581.15109.4.camel@neuro> It may be a problem related to your library filename (at linking time) that does not match the name you defined in the boot python module: BOOST_PYTHON_MODULE(core) requires for example "core.so" for the name of your library file (at least on linux). Nicolas On Tue, 2006-11-28 at 13:08 +0100, David Sveningsson wrote: > Hi, I am quite new at extending python with c++. I am using the boost > libraries on gnu/linux. I have many classes (with inheritance) that I > would like to expose to python. Is there some way to have many python > modules in one file? > > Like, core.so contains a string class and a memory class. I tried just > compiling everything as a shared library and importing into python with > "import core.string" but then I get the error "ImportError: dynamic > module does not define init function (initcore)" > > Im not really sure what that means. > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig From ext at sidvind.com Tue Nov 28 17:24:56 2006 From: ext at sidvind.com (David Sveningsson) Date: Tue, 28 Nov 2006 17:24:56 +0100 Subject: [C++-sig] Multiple modules in a file In-Reply-To: <1164726581.15109.4.camel@neuro> References: <456C26D7.2090206@sidvind.com> <1164726581.15109.4.camel@neuro> Message-ID: <456C62D8.7070008@sidvind.com> Nicolas Rougier skrev: > It may be a problem related to your library filename (at linking time) > that does not match the name you defined in the boot python module: > > BOOST_PYTHON_MODULE(core) > requires for example "core.so" for the name of your library file (at > least on linux). > Yes, but if I have multiple modules in a file it doesn't work > > Nicolas > > > On Tue, 2006-11-28 at 13:08 +0100, David Sveningsson wrote: > >> Hi, I am quite new at extending python with c++. I am using the boost >> libraries on gnu/linux. I have many classes (with inheritance) that I >> would like to expose to python. Is there some way to have many python >> modules in one file? >> >> Like, core.so contains a string class and a memory class. I tried just >> compiling everything as a shared library and importing into python with >> "import core.string" but then I get the error "ImportError: dynamic >> module does not define init function (initcore)" >> >> Im not really sure what that means. >> _______________________________________________ >> C++-sig mailing list >> C++-sig at python.org >> http://mail.python.org/mailman/listinfo/c++-sig >> > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > > From kelly.burkhart at gmail.com Wed Nov 29 14:31:28 2006 From: kelly.burkhart at gmail.com (Kelly Burkhart) Date: Wed, 29 Nov 2006 07:31:28 -0600 Subject: [C++-sig] compile error in iterator In-Reply-To: References: Message-ID: More info: I have two windows machines both with MSVS.Net 2003. The one that doesn't work is a recent install with compiler version 13.10.6030. My older machine has compiler version 13.10.3077. Has anyone else noticed problems compiling boost python iterators with recent MS compilers? -K On 11/27/06, Kelly Burkhart wrote: > I have a GzipFile class which exposes a gzipped file as a python file. > I have written an iterator over this class which I use to iterate > over an instance of this class. > > I'm using 1.33.1 and my code compiles cleanly and works on Linux g++ > 3.3.5. I am now trying to build on Windows using msvc.net (cl > 13.10.6030). This compiler complains that > bost::python::objects::iterator_range::next is > not accessible (full compiler complaint below). > > Does anyone have a solution, or hint to how I can go about fixing > this? Thank you in advance for any assistance. > > This code reproduces the problem: > > > #include > #include > #include > #include > > using namespace boost::python; > > //-------------------------------------------------------------------------------------------------- > // > class ItTstIterator : public boost::iterator_facade< ItTstIterator, > std::string, > > boost::forward_traversal_tag, > std::string > > { > public: > ItTstIterator( std::vector::iterator it ) : it_(it) {} > virtual ~ItTstIterator() {} > > private: > friend class boost::iterator_core_access; > > void increment() { ++it_; } > bool equal( const ItTstIterator &it ) const { return it_ == it.it_; } > std::string dereference() const { return *it_; } > > private: > std::vector::iterator it_; > }; > > //-------------------------------------------------------------------------------------------------- > class ItTst { > public: > typedef ItTstIterator iterator; > > ItTst() { vec_.push_back("one");vec_.push_back("two");vec_.push_back("three"); > } > ~ItTst() {} > > // For iteration > ItTstIterator begin() { return ItTstIterator( vec_.begin() ); } > ItTstIterator end() { return ItTstIterator( vec_.end() ); } > > private: > std::vector< std::string > vec_; > }; > > void wrapPyIter() > { > class_("ItTst", init<>() ) > .def("__iter__", iterator()) > ; > } > > > > And here is the full compiler complaint: > > cl -c -nologo -GX -GR -Zc:forScope -wd4101 -wd4290 -wd4100 -wd4189 > -DWIN32 -Zi -Od -D_DEBUG -DFD_SETSIZE=512 -MDd -Zi -Od -D_DEBUG > -DFD_SETSIZE=512 -MDd -DBOOST_SIGNALS_NAMESPACE=tb_signals -D__x86__ > -D__NT__ -D__OSVERSION__=5 -D__WIN32__ -GR -EHsc -W3 -w34100 -w34189 > -DWIN32 -DQT_LARGEFILE_SUPPORT -DCOMPILE_DL=1 -DQT_DLL -DQT_PLUGIN > -DQT_QT3SUPPORT_LIB -DQT3_SUPPORT -DQT_XML_LIB -DQT_GUI_LIB > -DQT_NETWORK_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT > -D_WIN32_WINNT=0x0500 -DFD_SETSIZE=512 -DNOMINMAX > -I"C:/Qt/4.2.1/include/QtCore" -I"C:/Qt/4.2.1/include/QtCore" > -I"C:/Qt/4.2.1/include/QtNetwork" -I"C:/Qt/4.2.1/include/QtNetwork" > -I"C:/Qt/4.2.1/include/QtGui" -I"C:/Qt/4.2.1/include/QtGui" > -I"C:/Qt/4.2.1/include/QtXml" -I"C:/Qt/4.2.1/include/QtXml" > -I"C:/Qt/4.2.1/include/Qt3Support" -I"C:/Qt/4.2.1/include/Qt3Support" > -I"C:/Qt/4.2.1/include" -I"..\Common" -I"..\libtbut" > -I"C:/Qt/4.2.1/include/ActiveQt" -I"moc" -I"..\libtbut" -I"ui" > -I"C:/postgresql\src\interfaces\libpq" -I"C:/postgresql\src\include" > -I"C:/Python25/include" -I"C:/Boost/include/boost-1_33_1" > -I"c:\omni\omniORB-4.0.3\include" > -I"c:\Qt\4.2.1\mkspecs\win32-msvc.net" -Fodebug\ > @c:\DOCUME~1\kelly\LOCALS~1\Temp\nm99.tmp > wrap_py_iter.cpp > C:/Boost\include\boost-1_33_1\boost\detail\compressed_pair.hpp(347) : > error C2247: 'boost::python::objects::iterator_range::next' > not accessible because > 'boost::details::compressed_pair_imp' uses 'private' to > inherit from 'boost::python::objects::iterator_range::next' > with > [ > NextPolicies=boost::python::return_value_policy, > Iterator=iterator_const > ] > and > [ > T1=boost::python::objects::iterator_range,iterator_const>::next, > T2=boost::python::return_value_policy, > Version=3 > ] > and > [ > NextPolicies=boost::python::return_value_policy, > Iterator=iterator_const > ] > C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(51) > : see declaration of > 'boost::python::objects::iterator_range::next' > with > [ > NextPolicies=boost::python::return_value_policy, > Iterator=iterator_const > ] > C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(51) > : see declaration of > 'boost::python::objects::iterator_range::next' > with > [ > NextPolicies=boost::python::return_value_policy, > Iterator=iterator_const > ] > C:/Boost\include\boost-1_33_1\boost\python\detail\caller.hpp(212) > : see reference to class template instantiation > 'boost::compressed_pair' being compiled > with > [ > T1=boost::python::objects::iterator_range,iterator_const>::next, > T2=boost::python::return_value_policy > ] > C:/Boost\include\boost-1_33_1\boost\python\detail\caller.hpp(145) > : see reference to class template instantiation > 'boost::python::detail::caller_arity<1>::impl' being > compiled > with > [ > F=boost::python::objects::iterator_range,iterator_const>::next, > Policies=boost::python::return_value_policy, > Sig=boost::mpl::vector2 > ] > C:/Boost\include\boost-1_33_1\boost\python\make_function.hpp(37) > : see reference to class template instantiation > 'boost::python::detail::caller' being compiled > with > [ > F=boost::python::objects::iterator_range,iterator_const>::next, > CallPolicies=boost::python::return_value_policy, > Sig=boost::mpl::vector2 > ] > C:/Boost\include\boost-1_33_1\boost\python\make_function.hpp(89) > : see reference to function template instantiation > 'boost::python::api::object > boost::python::detail::make_function_aux(F,const > CallPolicies &,const Sig &)' being compiled > with > [ > F=boost::python::objects::iterator_range,iterator_const>::next, > CallPolicies=boost::python::return_value_policy, > Signature=boost::mpl::vector2, > Sig=boost::mpl::vector2 > ] > C:/Boost\include\boost-1_33_1\boost\python\make_function.hpp(129) > : see reference to function template instantiation > 'boost::python::api::object > boost::python::detail::make_function_dispatch(F,const > CallPolicies &,const Signature &,boost::mpl::false_)' being compiled > with > [ > F=boost::python::objects::iterator_range,iterator_const>::next, > CallPolicies=boost::python::return_value_policy, > KeywordsOrSignature=boost::mpl::vector2, > Signature=boost::mpl::vector2 > ] > C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(137) > : see reference to function template instantiation > 'boost::python::api::object > boost::python::make_function::next,NextPolicies,boost::mpl::vector2>(F,const > CallPolicies &,const KeywordsOrSignature &)' being compiled > with > [ > NextPolicies=boost::python::return_value_policy, > Iterator=iterator_const, > T0=result_type, > T1=range_ &, > F=boost::python::objects::iterator_range,iterator_const>::next, > CallPolicies=boost::python::return_value_policy, > KeywordsOrSignature=boost::mpl::vector2 > ] > C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(163) > : see reference to function template instantiation > 'boost::python::api::object > boost::python::objects::detail::demand_iterator_class>(const > char *,Iterator *,const NextPolicies &)' being compiled > with > [ > Iterator=const iterator_const, > ResultConverterGenerator=boost::python::return_by_value, > NextPolicies=boost::python::return_value_policy > ] > C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(161) > : while compiling class-template member function > 'boost::python::objects::iterator_range > boost::python::objects::detail::py_iter_::operator > ()(boost::python::back_reference) const' > with > [ > NextPolicies=boost::python::return_value_policy, > Iterator=iterator_const, > Target=ItTst, > Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > T=ItTst & > ] > C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(187) > : see reference to class template instantiation > 'boost::python::objects::detail::py_iter_' > being compiled > with > [ > Target=ItTst, > Iterator=iterator_const, > Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > NextPolicies=boost::python::return_value_policy > ] > C:/Boost\include\boost-1_33_1\boost\python\object\iterator.hpp(239) > : see reference to function template instantiation > 'boost::python::api::object > boost::python::objects::detail::make_iterator_function(const > Accessor1 &,const Accessor2 &,const NextPolicies &,Iterator &(__cdecl > *)(void),boost::type *,int)' being compiled > with > [ > Target=ItTst, > T=const iterator_const, > NextPolicies=boost::python::return_value_policy, > Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > Iterator=const iterator_const > ] > C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(39) : > see reference to function template instantiation > 'boost::python::api::object > boost::python::objects::make_iterator_function,boost::_bi::protected_bind_t>(const > Accessor1 &,const Accessor2 &,const NextPolicies &,boost::type *)' > being compiled > with > [ > Target=ItTst, > NextPolicies=boost::python::return_value_policy, > F=boost::_bi::bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>, > Accessor1=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > Accessor2=boost::_bi::protected_bind_t::apply::iterator,boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst > &),boost::_bi::list1>::B1>>>, > T=ItTst > ] > C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(96) : > see reference to function template instantiation > 'boost::python::api::object > boost::python::detail::make_iterator::apply::iterator(__cdecl > *)(T &),boost::python::detail::iterators_impl::apply::iterator(__cdecl > *)(T &),boost::python::return_value_policy>(Accessor1,Accessor2,NextPolicies,Target > &(__cdecl *)(void))' being compiled > with > [ > T=ItTst, > const_=false, > ResultConverterGenerator=boost::python::return_by_value, > Accessor1=boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst &), > Accessor2=boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst &), > NextPolicies=boost::python::return_value_policy, > Target=ItTst > ] > C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(120) : > see reference to function template instantiation > 'boost::python::api::object > boost::python::range::apply::iterator(__cdecl > *)(T &),boost::python::detail::iterators_impl::apply::iterator(__cdecl > *)(T &)>(Accessor1,Accessor2,NextPolicies *)' being compiled > with > [ > NextPolicies=boost::python::objects::default_iterator_call_policies, > const_=false, > T=ItTst, > Accessor1=boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst &), > Accessor2=boost::python::detail::iterators_impl::apply::iterator > (__cdecl *)(ItTst &) > ] > C:/Boost\include\boost-1_33_1\boost\python\iterator.hpp(116) : > while compiling class-template member function > 'boost::python::iterator::iterator(void)' > with > [ > Container=ItTst > ] > wrap_py_iter.cpp(48) : see reference to class template > instantiation 'boost::python::iterator' being compiled > with > [ > Container=ItTst > ] > NMAKE : fatal error U1077: 'cl' : return code '0x2' > Stop. > NMAKE : fatal error U1077: '"c:\Program Files\Microsoft Visual Studio > .NET 2003\VC7\BIN\nmake.exe"' : return code '0x2' > Stop. > From greg.landrum at gmail.com Wed Nov 29 14:55:46 2006 From: greg.landrum at gmail.com (Greg Landrum) Date: Wed, 29 Nov 2006 14:55:46 +0100 Subject: [C++-sig] compile error in iterator In-Reply-To: References: Message-ID: <60825b0f0611290555l133a7a29n3415c62b26ac8db4@mail.gmail.com> On 11/29/06, Kelly Burkhart wrote: > More info: I have two windows machines both with MSVS.Net 2003. The > one that doesn't work is a recent install with compiler version > 13.10.6030. My older machine has compiler version 13.10.3077. > > Has anyone else noticed problems compiling boost python iterators with > recent MS compilers? I have noticed exactly this problem with the newer compiler version. I assumed that it was a mistake somewhere in my code, but I haven't been able to track it down yet. I'm glad to see that it's not just me. -greg From kir at lapshin.net Thu Nov 30 10:43:04 2006 From: kir at lapshin.net (Kirill Lapshin) Date: Thu, 30 Nov 2006 12:43:04 +0300 Subject: [C++-sig] py++ and std::bitset Message-ID: Roman, Currently py++ (or, rather pygccxml) complains about std::bitset. It is a mere warning, and does not affect me -- I am not exposing any bitsets to python yet. Still I am a bit worrying that I might have such a need in future. It might very well be that this warning is really harmless in this particular case, and can be ignored. Could you verify my analysis? I am using gccxml from CVS (reasonably recent, though not the latest) built on cygwin, cygwin gcc 3.4.4, Py++ and pygccxml 0.8.2. The problem arises from _Base_bitset that has member _WordT _M_w[_Nw]. Gccxml reports that max for this array is (_Nw-1) which pygccxml does not recognize (it expects a number). _Base_bitset is a private base of std::bitset. I am getting warning: UserWarning: unable to find out array size from expression "(_Nw - 1)" I suppose that won't affect exposing bitset since it is a member of private base, which I don't really have (and can't) expose anyways. Is it so? Can something be done on pygccxml to support templated arrays, and effectively remove this warning? Regards, Kirill From roman.yakovenko at gmail.com Thu Nov 30 11:08:25 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 30 Nov 2006 12:08:25 +0200 Subject: [C++-sig] py++ and std::bitset In-Reply-To: References: Message-ID: <7465b6170611300208h677673d6p8de9aa3f2900db6a@mail.gmail.com> On 11/30/06, Kirill Lapshin wrote: > Roman, > > Currently py++ (or, rather pygccxml) complains about std::bitset. It is > a mere warning, and does not affect me -- I am not exposing any bitsets > to python yet. Still I am a bit worrying that I might have such a need > in future. It might very well be that this warning is really harmless in > this particular case, and can be ignored. You are right, the warning could be ignored. > Could you verify my analysis? Yes. > The problem arises from _Base_bitset that has member _WordT > _M_w[_Nw]. Gccxml reports that max for this array is (_Nw-1) which > pygccxml does not recognize (it expects a number). Right. Py++ exposes static arrays. In this case it should know the array size and it should be integer. (Hint: outside of class definition _Nw is undefined ). > _Base_bitset is a private base of std::bitset. > > I am getting warning: > UserWarning: unable to find out array size from expression "(_Nw - 1)" > > I suppose that won't affect exposing bitset since it is a member of > private base, which I don't really have (and can't) expose anyways. Right > Can something be done on pygccxml to support templated arrays I think is has nothing to do with template arrays, but with expression that defines array size and how GCC-XML reports it. I don't know if it is possible to change GCC-XML to generate actual size and not the expression. > and > effectively remove this warning? Yes. GCC-XML contains directory with patched header files. I think it should be possible to create new "bitset" "implementation", which does not introduce the problem. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From ext at sidvind.com Thu Nov 30 15:36:36 2006 From: ext at sidvind.com (David Sveningsson) Date: Thu, 30 Nov 2006 15:36:36 +0100 Subject: [C++-sig] Extending Python with not-basic-c++ Message-ID: <456EEC74.5090006@sidvind.com> Hi, I have a working C++ game. To make it easier to extend/control/whatever some kind of scripting support is required. I know Python isn't really a scripting language but it seems like the best choice. I should also note that my knowledge of python is very limited. I heard that embedding python isn't a good way so I'm about to extend python with my functionality. At first I would like to just replace my game loop from C++ to python. It's basically a class with a method that keeps looping until the game is finished. But this class and all other classes inherits from a common 'object' class. And all memory is allocated through a memory manager. Also, the object class is dependent on a couple of other classes. And circular dependencies is not uncommon. It is not possible to loose this coupling. When compiling a class module for python it says undefined symbol 'a class method here'. So I include that class-objectfile when I compile the module. Eventfully it works but I cant do like this. Can someone give me a few directions? I don't really understand how to do this. From seefeld at sympatico.ca Thu Nov 30 16:12:09 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 30 Nov 2006 10:12:09 -0500 Subject: [C++-sig] Extending Python with not-basic-c++ In-Reply-To: <456EEC74.5090006@sidvind.com> References: <456EEC74.5090006@sidvind.com> Message-ID: <456EF4C9.2000802@sympatico.ca> David Sveningsson wrote: > Hi, I have a working C++ game. To make it easier to > extend/control/whatever some kind of scripting support is required. I > know Python isn't really a scripting language but it seems like the best > choice. I should also note that my knowledge of python is very limited. > > I heard that embedding python isn't a good way so I'm about to extend Why not ? > python with my functionality. At first I would like to just replace my > game loop from C++ to python. It's basically a class with a method that > keeps looping until the game is finished. > > But this class and all other classes inherits from a common 'object' > class. And all memory is allocated through a memory manager. Also, the > object class is dependent on a couple of other classes. And circular > dependencies is not uncommon. It is not possible to loose this coupling. OK. So you want to keep control over your C++ object's memory allocation in C++. That probably means that all the object creation, as far as the python bindings are concerned, should happen through a factory, with objects marked 'non-copyable', and return-value-policies generally 'return-existing-object' or somesuch. > When compiling a class module for python it says undefined symbol 'a > class method here'. So I include that class-objectfile when I compile > the module. Eventfully it works but I cant do like this. You really ought to provide some more detail here if you expect anybody to be able to help. Some code snippets, together with the actual error message from your compiler. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From kelly.burkhart at gmail.com Thu Nov 30 16:21:28 2006 From: kelly.burkhart at gmail.com (Kelly Burkhart) Date: Thu, 30 Nov 2006 09:21:28 -0600 Subject: [C++-sig] compile error in iterator In-Reply-To: References: Message-ID: On 11/27/06, Kelly Burkhart wrote: > > I'm using 1.33.1 and my code compiles cleanly and works on Linux g++ > 3.3.5. I am now trying to build on Windows using msvc.net (cl > 13.10.6030). This compiler complains that > bost::python::objects::iterator_range::next is > not accessible (full compiler complaint below). The problem was private derivation in boost/detail/compressed_pair.hpp. The CVS HEAD version of this file replaced private derivation with protected. Replacing this one file in my 1.33.1 tree solved my problem. -K From ext at sidvind.com Thu Nov 30 16:46:50 2006 From: ext at sidvind.com (David Sveningsson) Date: Thu, 30 Nov 2006 16:46:50 +0100 Subject: [C++-sig] Extending Python with not-basic-c++ In-Reply-To: <456EF4C9.2000802@sympatico.ca> References: <456EEC74.5090006@sidvind.com> <456EF4C9.2000802@sympatico.ca> Message-ID: <456EFCEA.4050702@sidvind.com> Stefan Seefeld skrev: > David Sveningsson wrote: > >> Hi, I have a working C++ game. To make it easier to >> extend/control/whatever some kind of scripting support is required. I >> know Python isn't really a scripting language but it seems like the best >> choice. I should also note that my knowledge of python is very limited. >> >> I heard that embedding python isn't a good way so I'm about to extend >> > > Why not ? > What I heard was that python was not designed for this and thus the python C API isn' the best. Are you suggesting I should embedd instead? >> When compiling a class module for python it says undefined symbol 'a >> class method here'. So I include that class-objectfile when I compile >> the module. Eventfully it works but I cant do like this. >> > > You really ought to provide some more detail here if you expect anybody > to be able to help. Some code snippets, together with the actual error > message from your compiler As I said, it works but for each module I have to link against many of my c++ object files. So the same files is linked into many modules. What I mant to know if this is the way it has to be done or if there is a better way. Won't it be problematic if each module has it's own version of everything? Right now I am trying to put everything in a big module instead of spliting it up. From anderslanglands at gmail.com Thu Nov 30 19:42:52 2006 From: anderslanglands at gmail.com (anders langlands) Date: Thu, 30 Nov 2006 18:42:52 +0000 Subject: [C++-sig] boost::langbinding? Message-ID: <57ffdb9c0611301042j653b17cey81d3d71cc47a2994@mail.gmail.com> Whatever happened to boost::langbinding? Is the project completely dead in the water? It seemed like a pretty good idea to have one library to handle binding to all your favourite 'scripting languages' A -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Thu Nov 30 21:17:30 2006 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 30 Nov 2006 15:17:30 -0500 Subject: [C++-sig] Extending Python with not-basic-c++ In-Reply-To: <456EFCEA.4050702@sidvind.com> References: <456EEC74.5090006@sidvind.com> <456EF4C9.2000802@sympatico.ca> <456EFCEA.4050702@sidvind.com> Message-ID: <456F3C5A.8060408@sympatico.ca> David Sveningsson wrote: > Stefan Seefeld skrev: >> David Sveningsson wrote: >> >>> Hi, I have a working C++ game. To make it easier to >>> extend/control/whatever some kind of scripting support is required. I >>> know Python isn't really a scripting language but it seems like the best >>> choice. I should also note that my knowledge of python is very limited. >>> >>> I heard that embedding python isn't a good way so I'm about to extend >>> >> Why not ? >> > What I heard was that python was not designed for this and thus the > python C API isn' the best. Are you suggesting I should embedd instead? I'm not sure what it originally was designed for, but I can assure you that it works great as an embedded scripting environment. I'm not qualified to tell you the best strategy, as I don't know the context. In any case, it's not 'instead', as in order to script your application 'from within', you need to expose your API to some degree to the script's environment, anyhow. >>> When compiling a class module for python it says undefined symbol 'a >>> class method here'. So I include that class-objectfile when I compile >>> the module. Eventfully it works but I cant do like this. >>> >> You really ought to provide some more detail here if you expect anybody >> to be able to help. Some code snippets, together with the actual error >> message from your compiler > As I said, it works but for each module I have to link against many of > my c++ object files. So the same files is linked into many modules. What > I mant to know if this is the way it has to be done or if there is a > better way. Won't it be problematic if each module has it's own version > of everything? Don't you use shared libraries ? Sharing doesn't imply duplication. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin...