From pwinston at gmail.com Fri Aug 1 18:13:23 2008 From: pwinston at gmail.com (Philip Winston) Date: Fri, 1 Aug 2008 12:13:23 -0400 Subject: [C++-sig] application exit and shared_ptr In-Reply-To: <87provnrxe.fsf@mcbain.luannocracy.com> References: <33677e5d0807292014s5cae77cdm7fa02b0fc21e6645@mail.gmail.com> <87provnrxe.fsf@mcbain.luannocracy.com> Message-ID: <33677e5d0808010913t779bcd86h2e48b9e432a13e8c@mail.gmail.com> Thanks, wow so maybe we are wrong to use shared_ptr at all in our situation. Does weak_ptr work as nicely with Boost.Python, because shared_ptr works great and that's why we were using it. But weak_ptr semantics would be ideal. The main C++ application needs to be in charge, no interpreter variable should be able to prevent something from being deleted. Yet at the same time using a "stale" variable in Python can't crash the, it can throw but not crash everything. Does weak_ptr with Boost.Python behave like this? I can give it a try but any advice is helpful. We have a lot of Boost.Python classes exposed now, but have been ignoring this fundamental issue. Philip Winston pwinston at gmail.com On Wed, Jul 30, 2008 at 2:33 PM, David Abrahams wrote: > > on Tue Jul 29 2008, "Philip Winston" wrote: > >> I understand it is not possible to call Py_Finalize with Boost.Python. >> But is it possible to manually delete all variables from an embedded >> interactive interpreter? Would this be a way to to cause Python to >> release any shared_ptrs it is holding on to? > > That's essentially the same problem, because any Python object could be > holding a shared_ptr (indirectly). > > > -- > Dave Abrahams > BoostPro Computing > http://www.boostpro.com > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > From markus.woschank at gmail.com Fri Aug 1 23:55:51 2008 From: markus.woschank at gmail.com (Markus Woschank) Date: Fri, 01 Aug 2008 23:55:51 +0200 Subject: [C++-sig] boost::python and boost::shared_ptr strict weak ordering problem Message-ID: <48938667.1080906@gmail.com> Hi list, I'm getting a strange behaviour with shared_ptr objects as arguments of wrapped C++ functions. The problem occurs when i try to use the shared_ptr objects in a std::set which (AFAIK) uses strict weak ordering equivalence [ !(a ptr; static ptr create() { return ptr( new Toast() ); } private: Toast() {} }; bool ptr_equals_last(Toast::ptr p) { static Toast::ptr last; bool equal = !(p("Toast",no_init) .def("create",&Toast::create) .staticmethod("create"); ; def("ptr_equals_last",ptr_equals_last); } --- [ also available (for some time) on http://tmp.netst.at/python_module.cpp ] python test and output: --- Python 2.5.2 (r252:60911, Aug 1 2008, 22:31:18) [GCC 4.1.2 (Gentoo 4.1.2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ptr_test import Toast,ptr_equals_last >>> >>> t = Toast.create() # instance for testing >>> t >>> ptr_equals_last(None) # should return True ( empty == empty => equivalent ) True >>> ptr_equals_last(None) # should return True ( empty == empty => e. ) True >>> >>> ptr_equals_last(t) # should return False ( empty != t => not e. ) False >>> ptr_equals_last(t) # should return True ( t == t => e. ) False >>> ptr_equals_last(t) # should return True ( t == t => e. ) False >>> ptr_equals_last(None) # should return False ( t != empty => not e. ) False >>> ptr_equals_last(None) # should return True ( empty == empty => e. ) True --- [ also available (for some time) on http://tmp.netst.at/test.py ] PS: After debugging a little bit my wild guess is, that boost.python uses the shared_ptr objects with custom deleter function that decrements the python refcount. And such custom shared_ptrs are created every time a C++ function with an shared_ptr argument is called (while incrementing the python refcount). Which seems to work fine but (IMO) breaks the less than operator of boost::shared_ptr documented at [http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/shared_ptr.htm#functions] - but as already said, it's only a wild guess. Cheers, Markus From rwgk at yahoo.com Sat Aug 2 00:57:29 2008 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Fri, 1 Aug 2008 15:57:29 -0700 (PDT) Subject: [C++-sig] boost::python and boost::shared_ptr strict weak ordering problem Message-ID: <133366.52902.qm@web31401.mail.mud.yahoo.com> I think your guess is very good. I stumbled over this, too, a while ago: http://mail.python.org/pipermail/c++-sig/2006-March/010407.html This lead me to redesign my parent-child classes in order to completely avoid smart pointers in the interfaces (they are still used "under the hood"). Ralf > PS: After debugging a little bit my wild guess is, that boost.python > uses the shared_ptr objects with > custom deleter function that decrements the python refcount. And such > custom shared_ptrs are created > every time a C++ function with an shared_ptr argument is called (while > incrementing the python refcount). > Which seems to work fine but (IMO) breaks the less than operator of > boost::shared_ptr documented at > [http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/shared_ptr.htm#functions] > - but as already said, it's > only a wild guess. From william.marie at gmail.com Sat Aug 2 11:37:05 2008 From: william.marie at gmail.com (=?UTF-8?Q?William_Mari=C3=A9?=) Date: Sat, 2 Aug 2008 02:37:05 -0700 (PDT) Subject: [C++-sig] Generic Function Calls Message-ID: <18787671.post@talk.nabble.com> Hi, I'm using Boost Python and i would like to know if there is an easy way to call functions generically with N numbers of arguments a bit like this : void call( boost::python::object bpFunction, ... ) { // Here i want to find a way to call the bpFunction with the variable argument list } Thank you William Mari? -- View this message in context: http://www.nabble.com/Generic-Function-Calls-tp18787671p18787671.html Sent from the Python - c++-sig mailing list archive at Nabble.com. From william.marie at gmail.com Sat Aug 2 14:17:16 2008 From: william.marie at gmail.com (=?UTF-8?Q?William_Mari=C3=A9?=) Date: Sat, 2 Aug 2008 05:17:16 -0700 (PDT) Subject: [C++-sig] Problem with python-debugging Message-ID: <18788695.post@talk.nabble.com> Hi, I have a problem trying using python-debugging, the generated library for boost-python is called : boost_python-vc80-mt-gyd-1_35.dll but when i try to build an exe using it i have this error : LINK : fatal error LNK1104 : cannot open file 'libboost-python-vc80-mt-gd-1_35.lib' So i don't really understand why bjam doesn't try to link with the gyd library ? Could someone tell me why ? Thanks William Mari? -- View this message in context: http://www.nabble.com/Problem-with-python-debugging-tp18788695p18788695.html Sent from the Python - c++-sig mailing list archive at Nabble.com. From seefeld at sympatico.ca Sat Aug 2 16:59:05 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sat, 02 Aug 2008 10:59:05 -0400 Subject: [C++-sig] Generic Function Calls In-Reply-To: <18787671.post@talk.nabble.com> References: <18787671.post@talk.nabble.com> Message-ID: <48947639.9010506@sympatico.ca> William Mari? wrote: > Hi, > > I'm using Boost Python and i would like to know if there is an easy way to > call functions generically with N numbers of arguments a bit like this : > > void call( boost::python::object bpFunction, ... ) > { > // Here i want to find a way to call the bpFunction with the variable > argument list > } > Just a couple of days ago I have checked in support for this into the trunk (it's too late for the upcoming 36 release, but should be part of the next one). With that, you will be able to do void call(boost::python::object callable) { boost::python::list args; // ... now fill the list callable(*args); } HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From m.rogers at hef.ru.nl Sat Aug 2 23:04:38 2008 From: m.rogers at hef.ru.nl (Michael Rogers) Date: Sat, 2 Aug 2008 23:04:38 +0200 Subject: [C++-sig] boost python on os x 10.5, intel Message-ID: <18EC77C7-65C5-4C9A-A31E-72E12AB74E10@hef.ru.nl> I have figured out how to build and use python extensions under linux. When I try to run any of the examples on os x 10.5 (intel), the boost_1_35_0/libs/python/example/quickstart for example, it compiles a lot of stuff, then gets stuck at this line: darwin.link.dll bin/darwin/debug/macosx-version-10.4/extending.so it just sits there, bjam and the python and sh processes that it spawns show 0% cpu usage. If I Ctrl-c it, and do it again, then I get: ...using extending.so... instead. This link pretty much describes what is happening to me. http://article.gmane.org/gmane.comp.lib.boost.build/18302 Does anyone else experience this? Anyone know how to fix it? From merlin66b at gmail.com Sun Aug 3 07:28:00 2008 From: merlin66b at gmail.com (Thomas Berg) Date: Sun, 3 Aug 2008 05:28:00 +0000 (UTC) Subject: [C++-sig] Problem with python-debugging References: <18788695.post@talk.nabble.com> Message-ID: The problem is not bjam, but boost/config/auto_link.hpp. This header has hard- coded the naming convention of the boost debug libraries to "-gd", it just doesn't know about the "-gyd" convention for python debugging. I worked around the problem by disabling the autolink-feature, by defining "BOOST_ALL_NO_LIB" when building. Bjam already links to the correct "-gyd" version (I think), so this just prevents Visual Studio from pulling in the "- gd" in addition... Thomas From happybrowndog at hotmail.com Sun Aug 3 18:46:13 2008 From: happybrowndog at hotmail.com (happybrowndog) Date: Sun, 03 Aug 2008 09:46:13 -0700 Subject: [C++-sig] python-debugging=on can't open boost library during Link step Message-ID: When I bjam as follows: bjam python-debugging=on --preserve-test-targets --debug-configuration I get a link error that it can't open boost_python-vc90-mt-gd-1_34.lib . Without python-debugging=on, there are no errors. I'm using the default setup from the Boost distribution for windows. My toolset is msvc=9.0 and I'm building for python 2.5. I'm using the default Jamroot provided, and I'm trying to build the getting_started*.cpp files in the example. Is there a fix for this? Also, the reason I used python-debugging=on is because I would like to debug the python extension later using VC++ debugger. Is this what the option does? From hohehohe2 at gmail.com Mon Aug 4 09:18:45 2008 From: hohehohe2 at gmail.com (Koichi Tamura) Date: Mon, 4 Aug 2008 16:18:45 +0900 Subject: [C++-sig] static/dynamic boost::python conflicts? In-Reply-To: References: Message-ID: Hello, I've experienced a trouble about boost.python linking (or Python itself) and I've separated what is causing trouble from my source. The condition is - An application (m) loads two libraries dynamically. - One of them (a) creates a Python module, calls its init function, and uses it internally. boost.python is statically linked with (a). - The other (b) linkes boost.python dynamically - The application (m) loads (b) first, then loads (a) In this condition, (a)'s module is broken. If anybody experienced it, or knows what's going on and how to make the module working, please let me know. Thanks in advance. -Koichi Here's the test code. (a) is a.cpp and (b) is b.cpp, (m) is main.cpp here. $ cat a.cpp #include using namespace boost::python; struct World { std::string greet(){return "hello";} }; BOOST_PYTHON_MODULE(hello) { class_("World") .def("greet", &World::greet); } extern "C" { void pycall() { Py_Initialize(); PyRun_SimpleString("print 'pycall'"); inithello(); object o_main(handle<>(borrowed(PyImport_AddModule("__main__")))); object o_hello(handle<>(PyImport_ImportModule("hello"))); o_main.attr("hel") = o_hello; PyRun_SimpleString("print hel.World().greet()"); } } $ cat b.cpp $ cat main.cpp #include int main() { void* handle0 = dlopen("b.bundle", RTLD_NOW); void* handle = dlopen("a.bundle", RTLD_NOW); typedef void (*func)(); func myfunc; myfunc = (func)dlsym(handle, "pycall"); myfunc(); dlclose(handle); return 0; } $ gcc -o a.bundle -bundle -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -L/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config -lpython2.5 -lstdc++ a.cpp -lboost_python-mtstatic-1_35 $ gcc -o b.bundle -bundle -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -L/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/config -lpython2.5 -lstdc++ b.cpp -lboost_python-mt-1_35 $ gcc main.cpp -lstdc++ $ ./a.out pycall Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'World' I've tested some more. - It works if I comment out void* handle0 = dlopen("b.bundle", RTLD_NOW); - It works if I call dlclose(handle0) just after void* handle0 = dlopen("b.bundle", RTLD_NOW); - except inithello(); it is working fine. - It works if I separate the hello module, create hello.so, and import it later. - If I do one of the following things: 1) dynamically link a.bundle and boost::python 2) statically link b.bundle and boost::python 3) dynamically link a.bundle and boost::python, and statically link b.bundle and boost::python I cannot use PyImport_AppendInittab() nor PyImport_ExtendInittab(), since Python interpreter may be already running when my code is first executed. I can separate my extension but I'd rather not. 2008/7/23 Koichi Tamura > Hello, > I'm using boost::python and I've got a problem now. > > I'm writing a shared library(bundle, I'm using MacOSX10.5, and it's a > plug-in for some > application) where I have a code like this. > > //....on init.... > if ( ! Py_IsInitialized()) > { > int a = PyImport_AppendInittab("MyModule", &initMyModule); > Py_Initialize(); > PyEval_InitThreads(); > PyEval_ReleaseLock(); > } > > //....somewhere else... > PyGILState_STATE state = PyGILState_Ensure(); > module = object(handle<>(PyModule_New(moduleName))); > myMod = object(handle<>(PyImport_ImportModule("MyModule"))); > module.attr("mymod") = myMod; > PyGILState_Release(state); > > I statically linked boost::python, and it works fine. When imported, > MyModule is > filled with classes that boost::python has wrapped. > > But when I use another shared library(#) which dynamically links > boost::python > together with mine, PyImport_ImportModule("MyModule") returns a module > which dict > is empty but __doc__ and __name__. > > Instead of (#) I made a test shared library that does nothing but linking > boost::python dynamically, and it still fails. > > Why does all statically linked boost::python and extension is affected by a > dynamically > linked boost::python? I'm really puzzled. > > > I would really appreciate if anybody could help. > > -Koichi > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave at boostpro.com Wed Aug 6 17:03:13 2008 From: dave at boostpro.com (David Abrahams) Date: Wed, 06 Aug 2008 11:03:13 -0400 Subject: [C++-sig] application exit and shared_ptr In-Reply-To: <33677e5d0808010913t779bcd86h2e48b9e432a13e8c@mail.gmail.com> (Philip Winston's message of "Fri, 1 Aug 2008 12:13:23 -0400") References: <33677e5d0807292014s5cae77cdm7fa02b0fc21e6645@mail.gmail.com> <87provnrxe.fsf@mcbain.luannocracy.com> <33677e5d0808010913t779bcd86h2e48b9e432a13e8c@mail.gmail.com> Message-ID: <87ej52chji.fsf@mcbain.luannocracy.com> on Fri Aug 01 2008, "Philip Winston" wrote: > Thanks, wow so maybe we are wrong to use shared_ptr at all in our > situation. Does weak_ptr work as nicely with Boost.Python, No, there's no built-in support for weak_ptr. It wouldn't be (too) hard to add, though. > because > shared_ptr works great and that's why we were using it. But weak_ptr > semantics would be ideal. The main C++ application needs to be in > charge, no interpreter variable should be able to prevent something > from being deleted. Yet at the same time using a "stale" variable in > Python can't crash the, it can throw but not crash everything. Does > weak_ptr with Boost.Python behave like this? No, weak_ptr isn't actually a ptr. So here's the question: if we implemented a holder-by-weak_ptr, what would the semantics be when the object has been released and it is passed to a function accepting a shared_ptr? Specifically, should we throw or should we generate an empty shared_ptr? Note, if it's the latter, and your C++ code assumes a valid pointee, it will crash. -- Dave Abrahams BoostPro Computing http://www.boostpro.com From dave at boostpro.com Wed Aug 6 17:37:28 2008 From: dave at boostpro.com (David Abrahams) Date: Wed, 06 Aug 2008 11:37:28 -0400 Subject: [C++-sig] boost python on os x 10.5, intel In-Reply-To: <18EC77C7-65C5-4C9A-A31E-72E12AB74E10@hef.ru.nl> (Michael Rogers's message of "Sat, 2 Aug 2008 23:04:38 +0200") References: <18EC77C7-65C5-4C9A-A31E-72E12AB74E10@hef.ru.nl> Message-ID: <87wsiub1dz.fsf@mcbain.luannocracy.com> on Sat Aug 02 2008, Michael Rogers wrote: > This link pretty much describes what is happening to me. > > http://article.gmane.org/gmane.comp.lib.boost.build/18302 > > Does anyone else experience this? Anyone know how to fix it? Looks like a bug in either Darwin's linker (hangs) or in its implementation of execwait. bjam is just waiting for the linker process to complete. My suggestion, to find out which: run bjam again with -n -a (build nothing) or -d+2 (rebuild what's out of date) and look at the linker command that bjam is issuing. Then try it yourself from a shell prompt. If it hangs, you know it's the linker. If not, it's either a bug in execwait or a bug in the way bjam is using it. -- Dave Abrahams BoostPro Computing http://www.boostpro.com From pwinston at gmail.com Thu Aug 7 05:30:39 2008 From: pwinston at gmail.com (Philip Winston) Date: Wed, 6 Aug 2008 23:30:39 -0400 Subject: [C++-sig] application exit and shared_ptr In-Reply-To: <87ej52chji.fsf@mcbain.luannocracy.com> References: <33677e5d0807292014s5cae77cdm7fa02b0fc21e6645@mail.gmail.com> <87provnrxe.fsf@mcbain.luannocracy.com> <33677e5d0808010913t779bcd86h2e48b9e432a13e8c@mail.gmail.com> <87ej52chji.fsf@mcbain.luannocracy.com> Message-ID: <33677e5d0808062030j76ba612ucce66daa8475033f@mail.gmail.com> > No, weak_ptr isn't actually a ptr. So here's the question: if we > implemented a holder-by-weak_ptr, what would the semantics be when the > object has been released and it is passed to a function accepting a > shared_ptr? Specifically, should we throw or should we generate an > empty shared_ptr? Note, if it's the latter, and your C++ code assumes a > valid pointee, it will crash. In our case throwing would work great. In our case if someone is trying to use these variables they are doing something wrong, they are trying to refer to objects which are long gone. So it's okay if their interactive python commands or scripts fail immediately. We just don't want the whole application to crash on them. We're new to embedding Python and this whole concern is mostly hypothetical at this point. We realized the issue because at application exit we were asserting some shared_ptrs are unique. But if you've created certain variables in Python, those ptrs are no longer unique. Maybe we should just deal with that uncertainty, just have no asserts and know the interpreter might be holding references. And then as for memory usage, yes it's possible for the user to hold stuff in memory, but how common will that be and how much memory are we talking about? It might be something we live with an no one really cares or notices. But to be strictly correct, the weak_ptr support sounds ideal. Then someone has a variable "foo" pointing to something, it gets unloaded, they try to use foo and get an exception. Very clean. I think long term this would be a valuable capability. Philip Winston pwinston at gmail.com From dave at boostpro.com Thu Aug 7 07:02:28 2008 From: dave at boostpro.com (David Abrahams) Date: Thu, 07 Aug 2008 01:02:28 -0400 Subject: [C++-sig] application exit and shared_ptr In-Reply-To: <33677e5d0808062030j76ba612ucce66daa8475033f@mail.gmail.com> (Philip Winston's message of "Wed, 6 Aug 2008 23:30:39 -0400") References: <33677e5d0807292014s5cae77cdm7fa02b0fc21e6645@mail.gmail.com> <87provnrxe.fsf@mcbain.luannocracy.com> <33677e5d0808010913t779bcd86h2e48b9e432a13e8c@mail.gmail.com> <87ej52chji.fsf@mcbain.luannocracy.com> <33677e5d0808062030j76ba612ucce66daa8475033f@mail.gmail.com> Message-ID: <87bq058ljv.fsf@mcbain.luannocracy.com> on Wed Aug 06 2008, "Philip Winston" wrote: > But to be strictly correct, the weak_ptr support sounds ideal. Then > someone has a variable "foo" pointing to something, it gets unloaded, > they try to use foo and get an exception. Very clean. I think long > term this would be a valuable capability. Please enter a ticket in http://svn.boost.org, then. I don't know when I'll be able to get to this (paying work is keeping me very busy) but if we don't have a record it will surely get lost. Thanks, -- Dave Abrahams BoostPro Computing http://www.boostpro.com From happybrowndog at hotmail.com Thu Aug 7 09:32:00 2008 From: happybrowndog at hotmail.com (happybrowndog) Date: Thu, 07 Aug 2008 00:32:00 -0700 Subject: [C++-sig] import getting_started1 - "no module named getting_started1" when using python_d Message-ID: I used bjam to create the pyd files in the example, all created fine. When I use python to import getting_started1, there's no problem. But when I use python_d to do the same thing, I get a "ImportError: no module named getting_started1 [29800 refs]" error. I am using VC++ 9.0, and have built python.exe and python_d.exe from source, as well as python25.dll and python25_d.dll. It is also my bjam tool set. The reason I am interested in running it with python_d.exe is because I would like to be able to debug the extension with VC++ .... but I may be under the wrong assumption that using python_d.exe is a necessity for debugging. Is this true? Here is my jamfile: ****************** use-project boost : ../../.. ; project : requirements /boost/python//boost_python ; python-extension getting_started1 : getting_started1.cpp : multi : debug : on ; python-extension getting_started2 : getting_started2.cpp : multi : debug : on ; python-extension std_pair_ext : std_pair.cpp : multi : debug : on ; Here is my bjam command: ******************** c:\boost-jam-3.1.16\bin.ntx86\bjam --preserve-test-targets --debug-configuration Here is my user-config.jam file: ******************** using msvc : : "C:/Program Files/Microsoft Visual Studio 9.0/VC/bin/cl"; using python : 2.5 : C:/Python25 ; The following is the output of bjam with -o log.txt: *********************** call "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 >nul cl /Zm800 -nologo @"bin\msvc-9.0\debug\threading-multi\getting_started1.obj.rsp" call "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 >nul link /NOLOGO /INCREMENTAL:NO /DLL /DEBUG /subsystem:console /out:"bin\msvc-9.0\debug\threading-multi\getting_started1.pyd" /IMPLIB:"bin\msvc-9.0\debug\threading-multi\getting_started1.lib" /LIBPATH:"C:\Python25\libs" @"bin\msvc-9.0\debug\threading-multi\getting_started1.pyd.rsp" if %ERRORLEVEL% NEQ 0 EXIT %ERRORLEVEL% if exist "bin\msvc-9.0\debug\threading-multi\getting_started1.pyd.manifest" ( mt -nologo -manifest "bin\msvc-9.0\debug\threading-multi\getting_started1.pyd.manifest" "-outputresource:bin\msvc-9.0\debug\threading-multi\getting_started1.pyd;2" ) call "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 >nul cl /Zm800 -nologo @"bin\msvc-9.0\debug\threading-multi\getting_started2.obj.rsp" call "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 >nul link /NOLOGO /INCREMENTAL:NO /DLL /DEBUG /subsystem:console /out:"bin\msvc-9.0\debug\threading-multi\getting_started2.pyd" /IMPLIB:"bin\msvc-9.0\debug\threading-multi\getting_started2.lib" /LIBPATH:"C:\Python25\libs" @"bin\msvc-9.0\debug\threading-multi\getting_started2.pyd.rsp" if %ERRORLEVEL% NEQ 0 EXIT %ERRORLEVEL% if exist "bin\msvc-9.0\debug\threading-multi\getting_started2.pyd.manifest" ( mt -nologo -manifest "bin\msvc-9.0\debug\threading-multi\getting_started2.pyd.manifest" "-outputresource:bin\msvc-9.0\debug\threading-multi\getting_started2.pyd;2" ) call "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 >nul cl /Zm800 -nologo @"bin\msvc-9.0\debug\threading-multi\std_pair.obj.rsp" call "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86 >nul link /NOLOGO /INCREMENTAL:NO /DLL /DEBUG /subsystem:console /out:"bin\msvc-9.0\debug\threading-multi\std_pair_ext.pyd" /IMPLIB:"bin\msvc-9.0\debug\threading-multi\std_pair_ext.lib" /LIBPATH:"C:\Python25\libs" @"bin\msvc-9.0\debug\threading-multi\std_pair_ext.pyd.rsp" if %ERRORLEVEL% NEQ 0 EXIT %ERRORLEVEL% if exist "bin\msvc-9.0\debug\threading-multi\std_pair_ext.pyd.manifest" ( mt -nologo -manifest "bin\msvc-9.0\debug\threading-multi\std_pair_ext.pyd.manifest" "-outputresource:bin\msvc-9.0\debug\threading-multi\std_pair_ext.pyd;2" ) From kuroutadori at gmail.com Thu Aug 7 16:48:42 2008 From: kuroutadori at gmail.com (Geoff) Date: Thu, 07 Aug 2008 23:48:42 +0900 Subject: [C++-sig] Wrapping functions that take void* parameters Message-ID: <489B0B4A.60304@gmail.com> I'm trying to wrap a C++ library that is used for serial communications. It has functions such as: ssize_t Read (void * const buffer, size_t count); and ssize_t Write (const void * const buffer, size_t count); There are two issues here that I haven't been able to solve: 1) How to wrap the void pointers. Ideally, I'd like to be able to do things like pass in a buffer of raw data or a Python string and have it written. Half a day of searching hasn't turned up anything even vaguely related to this more recent than 2003, so I was hoping there may have been some progress since then. 2) The Read() method expects buffer to point to some pre-allocated space into which it can put the data that is read from the serial port. I'm not sure how I could wrap this, because just passing in a Python string or something doesn't guarantee that that string has enough space to store the data. My first instinct would be to write a wrapper function that allocates space based on count, then calls Read(), passing in a pointer to that space, but I don't know how I could return that to the Python side. Thanks, Geoff From gjcarneiro at gmail.com Thu Aug 7 17:17:31 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Thu, 7 Aug 2008 16:17:31 +0100 Subject: [C++-sig] Wrapping functions that take void* parameters In-Reply-To: <489B0B4A.60304@gmail.com> References: <489B0B4A.60304@gmail.com> Message-ID: 2008/8/7 Geoff > I'm trying to wrap a C++ library that is used for serial communications. It > has functions such as: > > ssize_t Read (void * const buffer, size_t count); > > and > > ssize_t Write (const void * const buffer, size_t count); > > There are two issues here that I haven't been able to solve: > > 1) How to wrap the void pointers. Ideally, I'd like to be able to do things > like pass in a buffer of raw data or a Python string and have it written. > Half a day of searching hasn't turned up anything even vaguely related to > this more recent than 2003, so I was hoping there may have been some > progress since then. > > 2) The Read() method expects buffer to point to some pre-allocated space > into which it can put the data that is read from the serial port. I'm not > sure how I could wrap this, because just passing in a Python string or > something doesn't guarantee that that string has enough space to store the > data. My first instinct would be to write a wrapper function that allocates > space based on count, then calls Read(), passing in a pointer to that space, > but I don't know how I could return that to the Python side. Normally this type of memory buffers are mapped to Python strings, since Python strings can hold NULL bytes. Use PyString_FromStringAndSize to convert from C to Python (return), and "s#" format chars in PyArg_ParseTuple* to convert from Python to C. -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave at boostpro.com Thu Aug 7 21:17:26 2008 From: dave at boostpro.com (David Abrahams) Date: Thu, 07 Aug 2008 15:17:26 -0400 Subject: [C++-sig] static/dynamic boost::python conflicts? In-Reply-To: (Koichi Tamura's message of "Mon, 4 Aug 2008 16:18:45 +0900") References: Message-ID: <873algprcp.fsf@mcbain.luannocracy.com> on Mon Aug 04 2008, "Koichi Tamura" wrote: > Hello, > I've experienced a trouble about boost.python linking (or Python itself) and I've separated what > is causing trouble from my source. > The condition is > > - An application (m) loads two libraries dynamically. > - One of them (a) creates a Python module, calls its init function, and uses it internally. > boost.python is statically linked with (a). > - The other (b) linkes boost.python dynamically > - The application (m) loads (b) first, then loads (a) > > In this condition, (a)'s module is broken. This must be Linux? > If anybody experienced it, or knows what's going on and how to make the module working, please > let me know. The problem is that Linux has a single global symbol space. If you're interested, you might look at the threads I posted in at http://gcc.gnu.org/ml/gcc/2002-05/threads.html#02965 If you want to avoid that effect, you might think about using the GCC -fvisibility option: http://www.nedprod.com/programs/gccvisibility.html -- Dave Abrahams BoostPro Computing http://www.boostpro.com From ope-devel at gmx.de Thu Aug 7 21:18:16 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Thu, 07 Aug 2008 21:18:16 +0200 Subject: [C++-sig] embedded python and redirect Message-ID: <489B4A78.9040204@gmx.de> Hi at this time I try to embed python and redirect stderr/stdout using the test attached. That's are my first steps in boost.python ;-) Well, the exception handling does not compile as expected, I've got a lot of errors - why? Anyway, this file is mixed from different tutorials from net. Unsolved is the problem on executing the real python command (py::object vs. PyObject* strategy)? Any hints here? How can I check that redirection was successfully? Thanks, Olaf -------------- next part -------------- A non-text attachment was scrubbed... Name: boost_python.cpp Type: text/x-c++src Size: 2832 bytes Desc: not available URL: From NurEinDummy at gmx.de Sun Aug 10 16:38:01 2008 From: NurEinDummy at gmx.de (Dummy) Date: Sun, 10 Aug 2008 16:38:01 +0200 Subject: [C++-sig] Boost::Python -- Huuge warning when using 'extract'. Message-ID: <3152E7C87ECF40558A3AE312CCEC5BA2@cellardoor> Hi, list! :D A boost::python warning drives me crazy... as it's huuuge... I'm using VS 2005 and the warning rises when doing an extract like here: list huhu; huhu.append(4); int mfour = extract(huhu[0]); ... I pasted the whole warning here: http://rafb.net/p/YGyPyg88.html What can I do to get rid of it? From konrad.hinsen at laposte.net Mon Aug 11 15:01:14 2008 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Mon, 11 Aug 2008 15:01:14 +0200 Subject: [C++-sig] boost python on os x 10.5, intel Message-ID: On 06.08.2008, at 11:57, David Abrahams wrote: > on Sat Aug 02 2008, Michael Rogers wrote: > > > This link pretty much describes what is happening to me. > > > > http://article.gmane.org/gmane.comp.lib.boost.build/18302 > > > > Does anyone else experience this? Anyone know how to fix it? > > Looks like a bug in either Darwin's linker (hangs) or in its > implementation of execwait. bjam is just waiting for the linker > process > to complete. > > My suggestion, to find out which: run bjam again with -n -a (build > nothing) or -d+2 (rebuild what's out of date) and look at the linker > command that bjam is issuing. Then try it yourself from a shell > prompt. If it hangs, you know it's the linker. If not, it's either a > bug in execwait or a bug in the way bjam is using it. I am running into exactly the same problem with Boost 1.35.0 under MacOS 10.4.11, both Intel and PowerPC platformst. Following your suggestion, I ran bjam with -n -a and found the following linker command: g++ -dynamiclib -install_name "extending.so" -L"/Library/Frameworks/ Python.framework/Versions/2.5/lib" -L"/Library/Frameworks/ Python.framework/Versions/2.5/lib/python2.5/config" -o "bin/darwin/ debug/macosx-version-10.4/extending.so" "bin/darwin/debug/macosx- version-10.4/extending.o" "/usr/local/boost_1_35_0/bin.v2/libs/python/ build/darwin/debug/macosx-version-10.4/libboost_python-d-1_35.dylib" -lpython2.5 -g -isysroot /Developer/SDKs/MacOSX10.4u.sdk -mmacosx- version-min=10.4 When I run this command line directly from the shell, it terminates immediately without any error message, producing the library file ./ bin/darwin/debug/macosx-version-10.4/extending.so I started the build procedure from scratch and interrupted bjam when it got stuck. I checked that the library had already been produced, and that it is identical to the one that I got when running g++ directly. Restarting bjam after interrupting it makes it hang again immediately, trying to execute the command DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/2.5/ lib:/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ config:/usr/local/boost_1_35_0/bin.v2/libs/python/build/darwin/debug/ macosx-version-10.4:/usr/local/boost_1_35_0/libs/python/example/ quickstart/bin/darwin/debug/macosx-version-10.4:$DYLD_LIBRARY_PATH export DYLD_LIBRARY_PATH So it looks like the problem is in bjam, not in the linker. It still in the current development trunk of boost, so I filed a bug report: http://svn.boost.org/trac/boost/ticket/2185 Konrad. From sipickles at hotmail.com Mon Aug 11 15:19:46 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Mon, 11 Aug 2008 14:19:46 +0100 Subject: [C++-sig] Extending Stackless Python Message-ID: Hi, I am quite new to Boost::python. I have got the examples in the boost directory to work with a standard python installation, however I want to use boost::python with stackless python. When I install Stackless, I then get errors when running bjam: extending.cpp C:\Python25\Include\Python.h(79) : fatal error C1083: Cannot open include file: 'stackless.h': No such file or directory Stackless.h is in C:/Python25/stackless. My MSVC IDE can see the file okay, it is in the include path. What am I missing here? Many thanks Simon Pickles -- Linux Counter: User# 424693 From dave at boostpro.com Mon Aug 11 19:02:58 2008 From: dave at boostpro.com (David Abrahams) Date: Mon, 11 Aug 2008 09:02:58 -0800 Subject: [C++-sig] boost python on os x 10.5, intel In-Reply-To: (Konrad Hinsen's message of "Mon, 11 Aug 2008 15:01:14 +0200") References: Message-ID: <87abfjmqm5.fsf@mcbain.luannocracy.com> on Mon Aug 11 2008, Konrad Hinsen wrote: > So it looks like the problem is in bjam, not in the linker. It still > in the current development trunk of boost, so I filed a bug report: > > http://svn.boost.org/trac/boost/ticket/2185 Thanks for your work on this. -- Dave Abrahams BoostPro Computing http://www.boostpro.com From william.marie at gmail.com Tue Aug 12 11:58:20 2008 From: william.marie at gmail.com (=?UTF-8?Q?William_Mari=C3=A9?=) Date: Tue, 12 Aug 2008 02:58:20 -0700 (PDT) Subject: [C++-sig] Python Static link Message-ID: <18941050.post@talk.nabble.com> Hi, I would like to link statically python25.lib to boost-python.lib and then link statically boost-python.lib to my script.lib. i can't find a way to do that. Could someone tell me if it's possible and if yes how to do it ? Thanks William -- View this message in context: http://www.nabble.com/Python-Static-link-tp18941050p18941050.html Sent from the Python - c++-sig mailing list archive at Nabble.com. From sipickles at hotmail.com Tue Aug 12 12:18:53 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Tue, 12 Aug 2008 11:18:53 +0100 Subject: [C++-sig] Building Boost::Stackless_Python - undefined symbol: PyUnicodeUCS4_FromEncodedObject Message-ID: Hi, Sorry for the cross post - I am lost over whether my problem resides with my Boost or Stackless Python build. I am attempting to extend Stackless Python on Ubuntu 8.04. I have built the examples in boost_1_35_0/libs/python/example/quickstart with bjam. This passes the tests if I run it with the default Ubuntu python installation (/usr/lib/python25). However it fails if I run it with the stackless python installation (/usr/local/lib/python25). I get the error: Trying: from extending import * Expecting nothing ********************************************************************** File "/home/simon/Dev/testSpace/boostPython/test_extending.py", line 6, in test_extending Failed example: from extending import * Exception raised: Traceback (most recent call last): File "/usr/local/lib/python2.5/doctest.py", line 1228, in __run compileflags, 1) in test.globs File "", line 1, in from extending import * ImportError: /usr/local/lib/libboost_python-gcc42-d-1_35.so.1.35.0: undefined symbol: PyUnicodeUCS4_FromEncodedObject I built libboost_python-gcc42-d-1_35.so.1.35.0 by pointing bjam at my stackless python installation: sudo bjam -sPYTHON_ROOT=/usr/local/lib/python25 -sPYTHON_VERSION=2.5 stage It is obviously some sort of Unicode error. I know ubuntu comes with unicode support, so is it a problem with my stackless build? How do I enable unicode when building stackless or test for its support? Thanks Si -- Linux Counter: User# 424693 _________________________________________________________________ Get Hotmail on your mobile from Vodafone http://clk.atdmt.com/UKM/go/107571435/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From niki at vintech.bg Tue Aug 12 12:38:21 2008 From: niki at vintech.bg (niki) Date: Tue, 12 Aug 2008 13:38:21 +0300 Subject: [C++-sig] Building Boost::Stackless_Python - undefined symbol: PyUnicodeUCS4_FromEncodedObject In-Reply-To: References: Message-ID: <48A1681D.3000504@vintech.bg> Simon Pickles wrote: > ImportError: /usr/local/lib/libboost_python-gcc42-d-1_35.so.1.35.0: > undefined symbol: PyUnicodeUCS4_FromEncodedObject There are 2 kind of Unicode python builds - UCS2 and UCS4. Check that python and stackless and boost use same kind. HTH Niki Spahiev From ope-devel at gmx.de Tue Aug 12 21:14:25 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Tue, 12 Aug 2008 21:14:25 +0200 Subject: [C++-sig] [boost.python] general questions Message-ID: <48A1E111.8000400@gmx.de> Hi, the basic of redirection works in the example attached. Anyway, there are at least two points: $ LANG=en g++ -I /usr/include/python2.5 boost_python.cpp -o boost_python -l python2.5 -l boost_python && ./boost_python CTor py_redirector("out: ") CTor py_redirector("err: ") Testing embedded python: out: Hello out: World err: Traceback (most recent call last): err: File "", line 1, in err: NameError err: : err: name 'Hello' is not defined DTor py_redirector("out: ") The line break after NameError comes probably from internal symbol lookup and is '\0' terminated string, isn't it? How can I beautify this even more resp. correct it? Any hints to this? Where is my destructor of the 2nd py_redirector("err: ") ??? It occours only on enabled Py_Finalize(). Seems not to be a good style to hold all created objects during lifetime (memory leaks ....) until application quits. How can I set/register some callbacks in C++ (at best at construction time on C++ call side) inside py_redirector to get the write output to a GUI (e.g. QTextBrowser)? Thanks, Olaf -------------- next part -------------- A non-text attachment was scrubbed... Name: boost_python.cpp Type: text/x-c++src Size: 4916 bytes Desc: not available URL: From sipickles at hotmail.com Wed Aug 13 10:07:28 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Wed, 13 Aug 2008 09:07:28 +0100 Subject: [C++-sig] bjam output Message-ID: Hi, I have finally got my head round boost python and I'm loving it. I am on Ubuntu Hardy, stackless python 2.5, gcc 4.2.3. Two questions: 1) how can I use bjam to output the built libraries into a different folder to /bin/gcc-4.2.3/debug? 2) is this actually a debug library? if so, how do I create release versions? Many thanks Simon -- Linux Counter: User# 424693 _________________________________________________________________ Win New York holidays with Kellogg?s & Live Search http://clk.atdmt.com/UKM/go/107571440/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.bilokon at lehman.com Thu Aug 14 10:24:50 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Thu, 14 Aug 2008 09:24:50 +0100 Subject: [C++-sig] Boost.Python: wrapping a method returning const std::string & Message-ID: Hi c++-sig, Sorry if this is supposed to be glaringly obvious, but I thought std::string types were pretty much fully supported in Boost.Python (looking at Boost 1.35.0). I'm trying to wrap a method const std::string& getName( ) const; This should be straightforward, right? I'm doing it like this: class_("Ccy", init<>()) .def("getName", &Ccy::getName) ; But in return I'm getting Error 6 error C2027: use of undefined type 'boost::python::detail::specify_a_return_value_policy_to_wrap_functions_ returning' E:\dev\external\boost\boost_1_35_0\boost\python\detail\caller.hpp 223 Is this because the string is returned by reference? Do I have to wrap the method? If so, I would be very much obliged if you could direct me to an example. Many thanks, Paul - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From ope-devel at gmx.de Thu Aug 14 10:45:46 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Thu, 14 Aug 2008 10:45:46 +0200 Subject: [C++-sig] Boost.Python: wrapping a method returning const std::string & In-Reply-To: References: Message-ID: <48A3F0BA.7050208@gmx.de> Bilokon, Paul schrieb: > Hi c++-sig, > > Sorry if this is supposed to be glaringly obvious, but I thought > std::string types were pretty much fully supported in Boost.Python > (looking at Boost 1.35.0). > > I'm trying to wrap a method > > const std::string& getName( ) const; > > This should be straightforward, right? > > I'm doing it like this: > > class_("Ccy", init<>()) > .def("getName", &Ccy::getName) > ; > > But in return I'm getting > > Error 6 error C2027: use of undefined type > 'boost::python::detail::specify_a_return_value_policy_to_wrap_functions_ > returning' > E:\dev\external\boost\boost_1_35_0\boost\python\detail\caller.hpp > 223 > > Is this because the string is returned by reference? Do I have to wrap > the method? If so, I would be very much obliged if you could direct me > to an example. Cool compiler error, it says what he expected: see http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/copy_const_reference.html. Please google, why this is you friend. Regards, Olaf From sipickles at hotmail.com Thu Aug 14 17:55:19 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Thu, 14 Aug 2008 16:55:19 +0100 Subject: [C++-sig] ImportError: dynamic module does not define init function Message-ID: Hi, Sometimes I come across this error when I try to import a library: ImportError: dynamic module does not define init function (initHybridBulletObject) What exactly does it mean, and how can I fix this? My code looks like this, and compiles with bjam: class CHybridBulletObject { .... } BOOST_PYTHON_MODULE(pyboost) { using namespace boost::python; class_("HybridBulletObject", init()) .def("GetName", &CHybridBulletObject::GetName) ; } Thanks for any advice Simon -- Linux User# 424693 From nat at lindenlab.com Thu Aug 14 17:56:18 2008 From: nat at lindenlab.com (Nat Goodspeed) Date: Thu, 14 Aug 2008 11:56:18 -0400 Subject: [C++-sig] Wrapping functions that take void* parameters In-Reply-To: <489B0B4A.60304@gmail.com> References: <489B0B4A.60304@gmail.com> Message-ID: <48A455A2.2030002@lindenlab.com> Geoff wrote: > I'm trying to wrap a C++ library that is used for serial communications. > It has functions such as: > > ssize_t Read (void * const buffer, size_t count); > > and > > ssize_t Write (const void * const buffer, size_t count); > > There are two issues here that I haven't been able to solve: > > 1) How to wrap the void pointers. Ideally, I'd like to be able to do > things like pass in a buffer of raw data or a Python string and have it > written. Half a day of searching hasn't turned up anything even vaguely > related to this more recent than 2003, so I was hoping there may have > been some progress since then. > > 2) The Read() method expects buffer to point to some pre-allocated space > into which it can put the data that is read from the serial port. I'm > not sure how I could wrap this, because just passing in a Python string > or something doesn't guarantee that that string has enough space to > store the data. My first instinct would be to write a wrapper function > that allocates space based on count, then calls Read(), passing in a > pointer to that space, but I don't know how I could return that to the > Python side. Isn't this what the Python buffer object is for? http://www.python.org/doc/2.5.2/lib/typesseq.html http://docs.python.org/api/bufferObjects.html From seefeld at sympatico.ca Thu Aug 14 18:00:57 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 14 Aug 2008 12:00:57 -0400 Subject: [C++-sig] ImportError: dynamic module does not define init function In-Reply-To: References: Message-ID: <48A456B9.8010501@sympatico.ca> Simon Pickles wrote: > Hi, > > Sometimes I come across this error when I try to import a library: > > ImportError: dynamic module does not define init function > (initHybridBulletObject) > > What exactly does it mean, and how can I fix this? Python requires a module 'Foo' to provide an 'initFoo' function as entry point. This is generated by BOOST_PYTHON_MODULE, so make sure the name you pass to that matches the name of your module. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From paul.bilokon at lehman.com Thu Aug 14 17:51:58 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Thu, 14 Aug 2008 16:51:58 +0100 Subject: [C++-sig] Boost.Python: wrapping a method returning const std::string & In-Reply-To: <48A3F0BA.7050208@gmx.de> References: <48A3F0BA.7050208@gmx.de> Message-ID: Hi Olaf, Thanks a lot. This was certainly an informative error message. As per your reply, the error was resolved by replacing .def("getName", &Ccy::getName) with .def("getName", &Ccy::getName, boost::python::return_value_policy( )) Regards, Paul -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Olaf Peter Sent: Thursday, August 14, 2008 9:46 AM To: Development of Python/C++ integration Subject: Re: [C++-sig] Boost.Python: wrapping a method returning const std::string & Bilokon, Paul schrieb: > Hi c++-sig, > > Sorry if this is supposed to be glaringly obvious, but I thought > std::string types were pretty much fully supported in Boost.Python > (looking at Boost 1.35.0). > > I'm trying to wrap a method > > const std::string& getName( ) const; > > This should be straightforward, right? > > I'm doing it like this: > > class_("Ccy", init<>()) > .def("getName", &Ccy::getName) > ; > > But in return I'm getting > > Error 6 error C2027: use of undefined type > 'boost::python::detail::specify_a_return_value_policy_to_wrap_function > s_ > returning' > E:\dev\external\boost\boost_1_35_0\boost\python\detail\caller.hpp > 223 > > Is this because the string is returned by reference? Do I have to wrap > the method? If so, I would be very much obliged if you could direct me > to an example. Cool compiler error, it says what he expected: see http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/copy_const_refer ence.html. Please google, why this is you friend. Regards, Olaf _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From sipickles at hotmail.com Fri Aug 15 12:17:20 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 15 Aug 2008 11:17:20 +0100 Subject: [C++-sig] ImportError: dynamic module does not define init function Message-ID: Ah I see it. Thanks, getting my head around this now... Stefan Seefeld wrote: > Simon Pickles wrote: >> Hi, >> >> Sometimes I come across this error when I try to import a library: >> >> ImportError: dynamic module does not define init function >> (initHybridBulletObject) >> >> What exactly does it mean, and how can I fix this? > > Python requires a module 'Foo' to provide an 'initFoo' function as > entry point. > This is generated by BOOST_PYTHON_MODULE, so make sure the name you > pass to that matches the name of your module. > > HTH, > Stefan > -- Linux Counter: User# 424693 _________________________________________________________________ Win New York holidays with Kellogg?s & Live Search http://clk.atdmt.com/UKM/go/107571440/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sipickles at hotmail.com Fri Aug 15 12:18:21 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 15 Aug 2008 11:18:21 +0100 Subject: [C++-sig] [SOLVED]Re: bjam output Message-ID: Ah, Its as simple as adding this to the project section of the jamroot: . Simon Pickles wrote: > Hi, > > I have finally got my head round boost python and I'm loving it. I am on > Ubuntu Hardy, stackless python 2.5, gcc 4.2.3. > > Two questions: > > 1) how can I use bjam to output the built libraries into a different > folder to /bin/gcc-4.2.3/debug? > > 2) is this actually a debug library? if so, how do I create release > versions? > > Many thanks > > Simon > > -- > Linux Counter: User# 424693 > > > > ------------------------------------------------------------------------ > Get fish-slapping on Messenger! Play Now > > ------------------------------------------------------------------------ > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > -- Linux Counter: User# 424693 _________________________________________________________________ Win New York holidays with Kellogg?s & Live Search http://clk.atdmt.com/UKM/go/107571440/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sipickles at hotmail.com Fri Aug 15 12:23:32 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 15 Aug 2008 11:23:32 +0100 Subject: [C++-sig] Overloading member function problem Message-ID: Hi, Given a class: /////////////////// class CLog { public: void Log( const boost::format& ); void Log( const std::string& ); }; void (CLog::*LogS)(const std::string&) = &CLog::Log; void (CLog::*LogF)(const boost::format&) = &CLog::Log; //////////////////// And this module Macro: /////////////////// BOOST_PYTHON_MODULE(HybridLog) { using namespace boost::python; class_("logInterface") .def("Log", &LogS) .def("Log", &LogF) ; } /////////////////// How come I am getting these errors: /boost/python/class.hpp:536: error: no matching function for call to ?get_signature(void (CLog::**&)(const std::string&), CLog*)? /boost/python/class.hpp:536: error: no matching function for call to ?get_signature(void (CLog::**&)(const std::string&), CLog*)? I've tried all sorts of variations! Thanks Simon -- Linux Counter: User# 424693 _________________________________________________________________ Get Hotmail on your mobile from Vodafone http://clk.atdmt.com/UKM/go/107571435/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sipickles at hotmail.com Fri Aug 15 12:42:00 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 15 Aug 2008 11:42:00 +0100 Subject: [C++-sig] [SOLVED]Re: bjam output Message-ID: hmm mailman or thunderbird doesn't like text which looks like HTML tags should have read: < location>. or (less-than)location(greater-than)period Simon Pickles wrote: > Ah, > > Its as simple as adding this to the project section of the jamroot: > > . > > Simon Pickles wrote: >> Hi, >> >> I have finally got my head round boost python and I'm loving it. I am on >> Ubuntu Hardy, stackless python 2.5, gcc 4.2.3. >> >> Two questions: >> >> 1) how can I use bjam to output the built libraries into a different >> folder to /bin/gcc-4.2.3/debug? >> >> 2) is this actually a debug library? if so, how do I create release >> versions? >> >> Many thanks >> >> Simon >> >> -- >> Linux Counter: User# 424693 >> >> >> >> ------------------------------------------------------------------------ >> Get fish-slapping on Messenger! Play Now >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> C++-sig mailing list >> C++-sig at python.org >> http://mail.python.org/mailman/listinfo/c++-sig >> > > -- > Linux Counter: User# 424693 > > > > ------------------------------------------------------------------------ > Get fish-slapping on Messenger! Play Now > > ------------------------------------------------------------------------ > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > -- Linux Counter: User# 424693 _________________________________________________________________ Win a voice over part with Kung Fu Panda & Live Search?? and?? 100?s of Kung Fu Panda prizes to win with Live Search http://clk.atdmt.com/UKM/go/107571439/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Fri Aug 15 13:29:25 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Fri, 15 Aug 2008 07:29:25 -0400 Subject: [C++-sig] Overloading member function problem In-Reply-To: References: Message-ID: <48A56895.30401@sympatico.ca> Simon Pickles wrote: > > How come I am getting these errors: > > /boost/python/class.hpp:536: error: no matching function for call to > ?get_signature(void (CLog::**&)(const std::string&), CLog*)? > /boost/python/class.hpp:536: error: no matching function for call to > ?get_signature(void (CLog::**&)(const std::string&), CLog*)? While boost.python knows (defines) how to convert std::string, it doesn't seem to know about boost::format. Try wrapping boost::format first, then your overload should be resolvable. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From sipickles at hotmail.com Fri Aug 15 14:09:37 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 15 Aug 2008 13:09:37 +0100 Subject: [C++-sig] Overloading member function problem Message-ID: Stefan Seefeld wrote: > Simon Pickles wrote: >> >> How come I am getting these errors: >> >> /boost/python/class.hpp:536: error: no matching function for call to >> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? >> /boost/python/class.hpp:536: error: no matching function for call to >> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? > > While boost.python knows (defines) how to convert std::string, it > doesn't seem to know about boost::format. Try wrapping boost::format > first, What does 'wrapping' mean? :) As in BOOST_PYTHON_MODULE wrapping? > then your overload should be resolvable. > > HTH, > Stefan > -- Linux Counter: User# 424693 _________________________________________________________________ Make a mini you on Windows Live Messenger! http://clk.atdmt.com/UKM/go/107571437/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Fri Aug 15 15:12:38 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Fri, 15 Aug 2008 09:12:38 -0400 Subject: [C++-sig] Overloading member function problem In-Reply-To: References: Message-ID: <48A580C6.4000908@sympatico.ca> Simon Pickles wrote: > > > Stefan Seefeld wrote: > > Simon Pickles wrote: > >> > >> How come I am getting these errors: > >> > >> /boost/python/class.hpp:536: error: no matching function for call to > >> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? > >> /boost/python/class.hpp:536: error: no matching function for call to > >> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? > > > > While boost.python knows (defines) how to convert std::string, it > > doesn't seem to know about boost::format. Try wrapping boost::format > > first, > > What does 'wrapping' mean? :) class_ format("format"); HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From troy at resophonic.com Fri Aug 15 16:04:33 2008 From: troy at resophonic.com (troy d. straszheim) Date: Fri, 15 Aug 2008 10:04:33 -0400 Subject: [C++-sig] Overloading member function problem In-Reply-To: <48A56895.30401@sympatico.ca> References: <48A56895.30401@sympatico.ca> Message-ID: <48A58CF1.402@resophonic.com> Stefan Seefeld wrote: > Simon Pickles wrote: >> >> How come I am getting these errors: >> >> /boost/python/class.hpp:536: error: no matching function for call to >> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? >> /boost/python/class.hpp:536: error: no matching function for call to >> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? > > While boost.python knows (defines) how to convert std::string, it > doesn't seem to know about boost::format. Try wrapping boost::format > first, then your overload should be resolvable. boost.python won't complain about the inability to convert things until *runtime*. The needed converters could easily be someplace that this compilation unit cannot see (like in a completely different python wrapper library). Looks to me like OP just forgot to pass a type argument to class_<> > class_("logInterface") > .def("Log", &LogS) > .def("Log", &LogF) -t From sipickles at hotmail.com Fri Aug 15 17:13:19 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 15 Aug 2008 16:13:19 +0100 Subject: [C++-sig] Overloading member function problem Message-ID: > > > Looks to me like OP just forgot to pass a type argument to class_<> > >> class_("logInterface") >> .def("Log", &LogS) >> .def("Log", &LogF) Apologies. Code actually reads: class_("logInterface") .def("Log", &LogS) .def("Log", &LogF) > > > -- Linux Counter: User# 424693 _________________________________________________________________ Win a voice over part with Kung Fu Panda & Live Search?? and?? 100?s of Kung Fu Panda prizes to win with Live Search http://clk.atdmt.com/UKM/go/107571439/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Fri Aug 15 17:25:58 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Fri, 15 Aug 2008 11:25:58 -0400 Subject: [C++-sig] Overloading member function problem In-Reply-To: References: Message-ID: <48A5A006.7090606@sympatico.ca> Simon Pickles wrote: > > > > > > > > Looks to me like OP just forgot to pass a type argument to class_<> > > > >> class_("logInterface") > >> .def("Log", &LogS) > >> .def("Log", &LogF) > Apologies. > > Code actually reads: > > class_("logInterface") > .def("Log", &LogS) > .def("Log", &LogF) I don't quite believe you. :-) As Troy pointed out, class_ is a class template, so you need to provide a template argument list to make this code valid. For example: class_("logInterface") .... HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From sipickles at hotmail.com Fri Aug 15 17:34:51 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Fri, 15 Aug 2008 16:34:51 +0100 Subject: [C++-sig] Overloading member function problem Message-ID: Stefan Seefeld wrote: > Simon Pickles wrote: >> >> >> Stefan Seefeld wrote: >>> Simon Pickles wrote: >>>> >>>> How come I am getting these errors: >>>> >>>> /boost/python/class.hpp:536: error: no matching function for call to >>>> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? >>>> /boost/python/class.hpp:536: error: no matching function for call to >>>> ?get_signature(void (CLog::**&)(const std::string&), CLog*)? >>> >>> While boost.python knows (defines) how to convert std::string, it >>> doesn't seem to know about boost::format. Try wrapping boost::format >>> first, >> >> What does 'wrapping' mean? :) > class_ format("format"); > Sorry, no effect. My module now looks like this: class CLog { public: void Log(const std::string&); void Log(const boost::format&); } void (CLog::*pLogString)(const std::string&) = &CLog::Log; void (CLog::*pLogFormat)(const boost::format&) = &CLog::Log; BOOST_PYTHON_MODULE(Hybrid) { using namespace boost::python; class_ format("format"); class_("CLog") .def("Log", &pLogString) .def("Log", &pLogFormat) ; } No change in the error tho: boost/python/class.hpp:536: error: no matching function for call to ?get_signature(void (CLog::**&)(const std::string&), CLog*)? Thanks Si -- Linux Counter: User# 424693 _________________________________________________________________ Make a mini you on Windows Live Messenger! http://clk.atdmt.com/UKM/go/107571437/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sipickles at hotmail.com Sat Aug 16 15:35:40 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 16 Aug 2008 14:35:40 +0100 Subject: [C++-sig] R_X86_64_PC32 error and -fPIC Message-ID: Hi I hope this is on topic. It may be a gcc problem, but its certainly caused by using bjam to link a c++ lib for boost::python. I should point out this whole area is new to me! Here's my error: ...updating 1 target... gcc.link.dll HybridBulletObject.so /usr/bin/ld: HybridModule.o: relocation R_X86_64_PC32 against `(anonymous namespace)::CHybridBulletObject::Init(boost::shared_ptr, std::basic_string, std::allocator > const&, unsigned int const&, float const&, float const&, float const&, float const&, float const&, float const&)' can not be used when making a shared object; recompile with -fPIC /usr/bin/ld: final link failed: Bad value collect2: ld returned 1 exit status Compile what with -fPIC? I have an AMD64 (ubuntu 8.04) system. I thought only shared libraries needed to be compiled with PIC, and I am only linking to static libraries in HybridBulletObject.so. So, assuming its talking about the shared library output by bjam, I tried modifying my user-config.jam to: using gcc : : : -fPIC ; using python : 2.5 : /usr/local ; #stackless python location but I can't see the -fPIC added to the command line produce by bjam: "g++" -o "HybridBulletObject.so" -Wl,-h -Wl,HybridBulletObject.so -shared -Wl,--start-group "HybridModule.o" "HybridBulletObject.o" "Log.o" "/home/simon/Source/bullet-2.70/out/linux/optimize/libs/libbulletdynamics.a" "/home/simon/Source/boost_1_35_0/bin.v2/libs/python/build/gcc-4.2.3/debug/libboost_python-gcc42-d-1_35.so.1.35.0" -Wl,-Bstatic -Wl,-Bdynamic -lutil -lpthread -ldl -Wl,--end-group -g ...failed gcc.link.dll HybridBulletObject.so... ...failed updating 1 target... Thanks Simon -- Linux User# 424693 From sipickles at hotmail.com Sat Aug 16 16:10:01 2008 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 16 Aug 2008 15:10:01 +0100 Subject: [C++-sig] R_X86_64_PC32 error and -fPIC In-Reply-To: References: Message-ID: sorry, that s Simon Pickles wrote: > Hi > > I hope this is on topic. It may be a gcc problem, but its certainly > caused by using bjam to link a c++ lib for boost::python. I should > point out this whole area is new to me! > > Here's my error: > > ...updating 1 target... > gcc.link.dll HybridBulletObject.so > /usr/bin/ld: HybridModule.o: relocation R_X86_64_PC32 against > `(anonymous > namespace)::CHybridBulletObject::Init(boost::shared_ptr, > std::basic_string, std::allocator > > const&, unsigned int const&, float const&, float const&, float const&, > float const&, float const&, float const&)' can not be used when making > a shared object; recompile with -fPIC > /usr/bin/ld: final link failed: Bad value > collect2: ld returned 1 exit status > > > Compile what with -fPIC? I have an AMD64 (ubuntu 8.04) system. I > thought only shared libraries needed to be compiled with PIC, and I am > only linking to static libraries in HybridBulletObject.so. > > So, assuming its talking about the shared library output by bjam, I > tried modifying my user-config.jam to: > > using gcc : : : -fPIC ; > using python : 2.5 : /usr/local ; #stackless python location sorry, should have been: using gcc : : : -fPIC ; using python : 2.5 : /usr/local ; Now, I can see -fPIC on the g++ compile command line. No effect on the error tho. Do I need to rebuild all my static libs with -fPIC too? I notice that the boost python module will compile and link if I only add const functions. Add a normal function and it baulks. Weird. Simon From gjcarneiro at gmail.com Sat Aug 16 16:38:28 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Sat, 16 Aug 2008 15:38:28 +0100 Subject: [C++-sig] R_X86_64_PC32 error and -fPIC In-Reply-To: References: Message-ID: 2008/8/16 Simon Pickles > sorry, that s > > Simon Pickles wrote: > >> Hi >> >> I hope this is on topic. It may be a gcc problem, but its certainly caused >> by using bjam to link a c++ lib for boost::python. I should point out this >> whole area is new to me! >> >> Here's my error: >> >> ...updating 1 target... >> gcc.link.dll HybridBulletObject.so >> /usr/bin/ld: HybridModule.o: relocation R_X86_64_PC32 against `(anonymous >> namespace)::CHybridBulletObject::Init(boost::shared_ptr, >> std::basic_string, std::allocator > >> const&, unsigned int const&, float const&, float const&, float const&, float >> const&, float const&, float const&)' can not be used when making a shared >> object; recompile with -fPIC >> /usr/bin/ld: final link failed: Bad value >> collect2: ld returned 1 exit status >> >> >> Compile what with -fPIC? I have an AMD64 (ubuntu 8.04) system. I thought >> only shared libraries needed to be compiled with PIC, and I am only linking >> to static libraries in HybridBulletObject.so. >> >> So, assuming its talking about the shared library output by bjam, I tried >> modifying my user-config.jam to: >> >> using gcc : : : -fPIC ; >> using python : 2.5 : /usr/local ; #stackless python location >> > sorry, should have been: > > using gcc : : : -fPIC ; > using python : 2.5 : /usr/local ; > > Now, I can see -fPIC on the g++ compile command line. No effect on the > error tho. > > Do I need to rebuild all my static libs with -fPIC too? If you are building a shared library then all the libraries that you depend on need to be shared as well, i.e. they all need to be compiled with -fPIC. You can't link static libraries into shared libraries (the difference between '.a archive' and 'static library' should be noted here, since you could have a .a archive containing only objects compiled with -fPIC). > > > I notice that the boost python module will compile and link if I only add > const functions. Add a normal function and it baulks. Weird. Not sure what "const function" means. I only know the concepts of "const method", and "static function". -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From troy at resophonic.com Sat Aug 16 17:28:41 2008 From: troy at resophonic.com (troy d. straszheim) Date: Sat, 16 Aug 2008 11:28:41 -0400 Subject: [C++-sig] error while formatting signature for arg is not a Python function Message-ID: <48A6F229.3040201@resophonic.com> I'm playing with Sphinx 0.4.3, trying to make some docs for wrapped classes. I'm getting the error error while formatting signature for arg is not a Python function where 'arg is not a Python function' is the TypeError you get when you call inspect.getargspec() of a wrapped member function. Appears to relate to this thread about doctests: http://mail.python.org/pipermail/c++-sig/2007-June/012481.html Has anybody looked further at this? -t From dave at boostpro.com Sat Aug 16 22:51:52 2008 From: dave at boostpro.com (David Abrahams) Date: Sat, 16 Aug 2008 12:51:52 -0800 Subject: [C++-sig] error while formatting signature for arg is not a Python function In-Reply-To: <48A6F229.3040201@resophonic.com> (troy d. straszheim's message of "Sat, 16 Aug 2008 11:28:41 -0400") References: <48A6F229.3040201@resophonic.com> Message-ID: <87k5egptsn.fsf@mcbain.luannocracy.com> on Sat Aug 16 2008, "troy d. straszheim" wrote: > I'm playing with Sphinx 0.4.3, trying to make some docs for wrapped classes. > I'm getting the error > > error while formatting signature for arg is not a Python function > > where 'arg is not a Python function' is the TypeError you get when you call > inspect.getargspec() of a wrapped member function. > Appears to relate to this thread about doctests: > > http://mail.python.org/pipermail/c++-sig/2007-June/012481.html > > Has anybody looked further at this? I'm afraid I never did look at it further. I'd be very happy if the the problem were solved, though :-) -- Dave Abrahams BoostPro Computing http://www.boostpro.com From william.marie at gmail.com Mon Aug 18 12:01:48 2008 From: william.marie at gmail.com (=?UTF-8?Q?William_Mari=C3=A9?=) Date: Mon, 18 Aug 2008 03:01:48 -0700 (PDT) Subject: [C++-sig] How to wrap a python function pointer ? Message-ID: <19028640.post@talk.nabble.com> Hi, I would like to wrap a python function pointer to a void (*c++fun)() pointer : typedef void (*fct_void_void)( void ); void addTimer( double dStartIn, double dTickTime, u32 iTickCount, fct_void_void bpFctCallback ) { ..... } BOOST_PYTHON_MODULE(ksys) { using namespace boost::python; def("addTimer", &addTimer); } here is my output : 1> ..\..\libs\boost\boost/python/converter/registered.hpp(41) : see reference to class template instantiation 'boost::add_cv' being compiled 1> with 1> [ 1> T=void (void) 1> ] 1> ..\..\libs\boost\boost/python/converter/registered_pointee.hpp(27) : see reference to class template instantiation 'boost::python::converter::registered' being compiled 1> with 1> [ 1> T=void (void) 1> ] 1> ..\..\libs\boost\boost/python/converter/arg_from_python.hpp(269) : see reference to class template instantiation 'boost::python::converter::registered_pointee' being compiled 1> with 1> [ 1> T=void (__cdecl *)(void) 1> ] 1> ..\..\libs\boost\boost/python/converter/arg_from_python.hpp(268) : while compiling class template member function 'boost::python::converter::pointer_arg_from_python::pointer_arg_from_python(PyObject *)' 1> with 1> [ 1> T=void (__cdecl *)(void) 1> ] 1> ..\..\libs\boost\boost/python/arg_from_python.hpp(70) : while compiling class template member function 'boost::python::arg_from_python::arg_from_python(PyObject *)' 1> with 1> [ 1> T=void (__cdecl *)(void) 1> ] 1> ..\..\libs\boost\boost/preprocessor/iteration/detail/local.hpp(43) : see reference to class template instantiation 'boost::python::arg_from_python' being compiled 1> with 1> [ 1> T=void (__cdecl *)(void) 1> ] 1> ..\..\libs\boost\boost/python/detail/caller.hpp(200) : while compiling class template member function 'PyObject *boost::python::detail::caller_arity<4>::impl::operator ()(PyObject *,PyObject *)' 1> with 1> [ 1> F=void (__cdecl *)(double,double,u32,fct_void_void), 1> Policies=boost::python::default_call_policies, 1> Sig=boost::mpl::vector5 1> ] 1> ..\..\libs\boost\boost/python/detail/caller.hpp(169) : see reference to class template instantiation 'boost::python::detail::caller_arity<4>::impl' being compiled 1> with 1> [ 1> F=void (__cdecl *)(double,double,u32,fct_void_void), 1> Policies=boost::python::default_call_policies, 1> Sig=boost::mpl::vector5 1> ] 1> ..\..\libs\boost\boost/python/make_function.hpp(37) : see reference to class template instantiation 'boost::python::detail::caller' being compiled 1> with 1> [ 1> F=void (__cdecl *)(double,double,u32,fct_void_void), 1> CallPolicies=boost::python::default_call_policies, 1> Sig=boost::mpl::vector5 1> ] 1> ..\..\libs\boost\boost/python/make_function.hpp(104) : see reference to function template instantiation 'boost::python::api::object boost::python::detail::make_function_aux>(F,const CallPolicies &,const Sig &)' being compiled 1> with 1> [ 1> T0=void, 1> T1=double, 1> T2=double, 1> T3=u32, 1> T4=fct_void_void, 1> F=void (__cdecl *)(double,double,u32,fct_void_void), 1> CallPolicies=boost::python::default_call_policies, 1> Sig=boost::mpl::vector5 1> ] 1> ..\..\libs\boost\boost/python/def.hpp(82) : see reference to function template instantiation 'boost::python::api::object boost::python::make_function(F)' being compiled 1> with 1> [ 1> F=void (__cdecl *)(double,double,u32,fct_void_void) 1> ] 1> ..\..\libs\boost\boost/python/def.hpp(91) : see reference to function template instantiation 'boost::python::api::object boost::python::detail::make_function1(T,...)' being compiled 1> with 1> [ 1> T=void (__cdecl *)(double,double,u32,fct_void_void) 1> ] 1> ..\..\libs\script\src\ksysmodule.cpp(35) : see reference to function template instantiation 'void boost::python::def(const char *,Fn)' being compiled 1> with 1> [ 1> Fn=void (__cdecl *)(double,double,u32,fct_void_void) 1> ] 1>..\..\libs\boost\boost/python/converter/registered.hpp(86) : error C2784: 'void boost::python::converter::detail::register_shared_ptr1(volatile const T *)' : could not deduce template argument for 'volatile const T *' from 'void (__cdecl *)(void)' 1> ..\..\libs\boost\boost/python/converter/registered.hpp(77) : see declaration of 'boost::python::converter::detail::register_shared_ptr1' 1> ..\..\libs\boost\boost/python/converter/registered.hpp(94) : see reference to function template instantiation 'const boost::python::converter::registration &boost::python::converter::detail::registry_lookup2(T (__cdecl &(__cdecl *)(void)))' being compiled 1> with 1> [ 1> T=void (void) 1> ] 1> ..\..\libs\boost\boost/python/converter/registered.hpp(105) : see reference to function template instantiation 'const boost::python::converter::registration &boost::python::converter::detail::registry_lookup1(boost::type)' being compiled 1> with 1> [ 1> T=void (__cdecl &)(void) 1> ] 1> ..\..\libs\boost\boost/python/converter/registered.hpp(105) : while compiling class template static data member 'const boost::python::converter::registration &boost::python::converter::detail::registered_base::converters' 1> with 1> [ 1> T=void (__cdecl &)(void) 1> ] 1> ..\..\libs\boost\boost/python/converter/registered.hpp(44) : see reference to class template instantiation 'boost::python::converter::detail::registered_base' being compiled 1> with 1> [ 1> T=void (__cdecl &)(void) 1> ] 1> ..\..\libs\boost\boost/python/converter/registered_pointee.hpp(27) : see reference to class template instantiation 'boost::python::converter::registered' being compiled 1> with 1> [ 1> T=void (void) 1> ] 1> ..\..\libs\boost\boost/python/converter/arg_from_python.hpp(269) : see reference to class template instantiation 'boost::python::converter::registered_pointee' being compiled 1> with 1> [ 1> T=void (__cdecl *)(void) 1> ] 1> ..\..\libs\boost\boost/python/converter/arg_from_python.hpp(268) : while compiling class template member function 'boost::python::converter::pointer_arg_from_python::pointer_arg_from_python(PyObject *)' 1> with 1> [ 1> T=void (__cdecl *)(void) 1> ] Could someone tell me how i can do that please ? Thank you William -- View this message in context: http://www.nabble.com/How-to-wrap-a-python-function-pointer---tp19028640p19028640.html Sent from the Python - c++-sig mailing list archive at Nabble.com. From paul.bilokon at lehman.com Mon Aug 18 16:41:37 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Mon, 18 Aug 2008 15:41:37 +0100 Subject: [C++-sig] Multiple Constructors Message-ID: Hi, I'm wondering if there is an example that demonstrates how one should deal with classes with multiple constructors with different signatures, e.g. scope in_Term = class_("Term", init<>()) .def(init()) .def(init()) .def(init()) I don't think this approach is valid. Many thanks, Paul - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From paul.bilokon at lehman.com Mon Aug 18 16:45:46 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Mon, 18 Aug 2008 15:45:46 +0100 Subject: [C++-sig] "Returning" to Scope Message-ID: Hi, I'm trying to figure out how I can "return" to a previously defined scope. Since the current scope is normally set via construction, this is the only method I could think of: #include #include using std::cout; using std::endl; struct Foo { struct Bar { int barVar1; static const int barVar2 = 22; Bar() : barVar1(18) { } }; int fooVar1; int fooVar2; static const int fooVar3 = 7; Bar fooBar; enum FooEnum { RED, GREEN, BLUE, }; Foo() : fooVar1(2), fooVar2(3) { } }; struct Baz { int bazVar1; static const int bazVar2 = 13; Baz() : bazVar1(11) { } }; using namespace boost::python; BOOST_PYTHON_MODULE(scoping) { scope in_scoping; scope in_Foo = class_("Foo") .def_readwrite("fooVar1", &Foo::fooVar1) .def_readwrite("fooVar2", &Foo::fooVar2) .def_readonly("fooVar3", &Foo::fooVar3) ; // The following line is not strictly speaking necessary, since "scope // in_Foo = ..." would have set the current scope to in_Foo. However, // we prefer explicit to implicit scope in_Foo_1(in_Foo); class_("Bar") .def_readwrite("barVar1", &Foo::Bar::barVar1) .def_readonly("barVar2", &Foo::Bar::barVar2) ; scope in_scoping_1(in_scoping); class_("Baz") .def_readwrite("bazVar1", &Baz::bazVar1) .def_readonly("bazVar2", &Baz::bazVar2) ; scope in_Foo_2(in_Foo); enum_("FooEnum") .value("RED", Foo::RED) .value("GREEN", Foo::GREEN) .value("BLUE", Foo::BLUE) ; } However, this approach is pretty messy, particularly keeping track of ..._1, ..._2, ..._3, etc. Is there a neater approach? Many thanks, Paul - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From troy at resophonic.com Mon Aug 18 17:07:45 2008 From: troy at resophonic.com (troy d. straszheim) Date: Mon, 18 Aug 2008 11:07:45 -0400 Subject: [C++-sig] error while formatting signature for arg is not a Python function In-Reply-To: <87k5egptsn.fsf@mcbain.luannocracy.com> References: <48A6F229.3040201@resophonic.com> <87k5egptsn.fsf@mcbain.luannocracy.com> Message-ID: <48A99041.1080605@resophonic.com> David Abrahams wrote: > on Sat Aug 16 2008, "troy d. straszheim" wrote: > >> I'm playing with Sphinx 0.4.3, trying to make some docs for wrapped classes. >> I'm getting the error >> >> error while formatting signature for arg is not a Python function >> >> where 'arg is not a Python function' is the TypeError you get when you call >> inspect.getargspec() of a wrapped member function. >> Appears to relate to this thread about doctests: >> >> http://mail.python.org/pipermail/c++-sig/2007-June/012481.html >> >> Has anybody looked further at this? > > I'm afraid I never did look at it further. I'd be very happy if the > the problem were solved, though :-) > This has recently been worked around / fixed on the trunk of sphinx. No more big red boxes in the generated html. Yay. Sphinx is some Really Good Stuff. I did spend some time hacking at this, and at this point am not sure there exists a problem on the boost.python side. The behavior of inspect.getargspec() is the same for builtin C functions that come packaged with python as for boost.python wrapped functions. Take the standard C package 'audioop': >>> import audioop, inspect >>> def f(x): pass ... >>> inspect.getargspec(f) (['x'], None, None, None) >>> inspect.getargspec(audioop.bias) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/inspect.py", line 742, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function So apparently when getargspec says 'not a Python function' it does mean 'Python' and not just 'function'. I don't know how this impacts the doctest stuff in the post mentioned above. Anyway, I have to get back to writing docs.... -t From troy at resophonic.com Mon Aug 18 17:14:30 2008 From: troy at resophonic.com (troy d. straszheim) Date: Mon, 18 Aug 2008 11:14:30 -0400 Subject: [C++-sig] Multiple Constructors In-Reply-To: References: Message-ID: <48A991D6.9030702@resophonic.com> Bilokon, Paul wrote: > Hi, > > I'm wondering if there is an example that demonstrates how one should > deal with classes with multiple constructors with different signatures, > e.g. There is. It is right in the docs. class_("World", init()) .def(init()) .def("greet", &World::greet) .def("set", &World::set) ; > scope in_Term = class_("Term", init<>()) > .def(init()) > .def(init()) > .def(init()) > > I don't think this approach is valid. You're going to have to be more specific than that. -t From paul.bilokon at lehman.com Mon Aug 18 17:43:41 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Mon, 18 Aug 2008 16:43:41 +0100 Subject: [C++-sig] Multiple Constructors In-Reply-To: <48A991D6.9030702@resophonic.com> References: <48A991D6.9030702@resophonic.com> Message-ID: Hi Troy, My apologies, thanks a lot for pointing this out. Kind regards, Paul -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of troy d. straszheim Sent: Monday, August 18, 2008 4:15 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Multiple Constructors Bilokon, Paul wrote: > Hi, > > I'm wondering if there is an example that demonstrates how one should > deal with classes with multiple constructors with different > signatures, e.g. There is. It is right in the docs. class_("World", init()) .def(init()) .def("greet", &World::greet) .def("set", &World::set) ; > scope in_Term = class_("Term", init<>()) > .def(init()) > .def(init()) > .def(init()) > > I don't think this approach is valid. You're going to have to be more specific than that. -t _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From troy at resophonic.com Mon Aug 18 18:07:48 2008 From: troy at resophonic.com (troy d. straszheim) Date: Mon, 18 Aug 2008 12:07:48 -0400 Subject: [C++-sig] "Returning" to Scope In-Reply-To: References: Message-ID: <48A99E54.7000205@resophonic.com> Bilokon, Paul wrote: > Hi, > > I'm trying to figure out how I can "return" to a previously defined > scope. Scopes essentially push and pop themselves off a static stack of scopes as they are created/destroyed, so you can generally just use... scopes: BOOST_PYTHON_MODULE(scope) { { scope s = class_ ... enum_ ... } { scope s = class_ ... enum_ ... } class_ ... } -t From paul.bilokon at lehman.com Mon Aug 18 18:11:45 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Mon, 18 Aug 2008 17:11:45 +0100 Subject: [C++-sig] "Returning" to Scope In-Reply-To: <48A99E54.7000205@resophonic.com> References: <48A99E54.7000205@resophonic.com> Message-ID: This is great, thanks a lot, Troy! Regards, Paul -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of troy d. straszheim Sent: Monday, August 18, 2008 5:08 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] "Returning" to Scope Bilokon, Paul wrote: > Hi, > > I'm trying to figure out how I can "return" to a previously defined > scope. Scopes essentially push and pop themselves off a static stack of scopes as they are created/destroyed, so you can generally just use... scopes: BOOST_PYTHON_MODULE(scope) { { scope s = class_ ... enum_ ... } { scope s = class_ ... enum_ ... } class_ ... } -t _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From troy at resophonic.com Mon Aug 18 19:24:51 2008 From: troy at resophonic.com (troy d. straszheim) Date: Mon, 18 Aug 2008 13:24:51 -0400 Subject: [C++-sig] Alternate packaging technique for bindings + pure python Message-ID: <48A9B063.8070503@resophonic.com> I'm in the process of trying to organize a large project that is about half-and-half python and c++. There are many components, each of which consists of both python and c++, and I'm trying to hide this from the user. These components should appear to be internally seamless. The docs: http://www.boost.org/doc/libs/1_36_0/libs/python/doc/tutorial/doc/html/python/techniques.html#python.creating_packages recommend putting the cpp bindings in nested libraries, like so (BTW, the directory listing in the docs is buggy): sounds/ __init__.py core/ __init__.py _core.so filters/ __init__.py _filters.so io/ __init__.py _io.so where e.g. core/__init__.py contains from _core import * this works, but it is leaky, the user still sees the underscores in the package names and docs, cpp wrapper authors have to remember these underscores.... the interface not as clean as it could be. If you organize things like this, instead: sounds/ __init__.py core.so core/ __init__.py foo.py bar.py filters.so filters/ __init__.py io.so io/ __init__.py You can use the following function: def load_pybindings(name, path): """ Merges python bindings from shared library 'name' into module 'name'. Use when you have a directory structure:: lib/ foo.so foo/ __init__.py something.py Here, inside ``foo/__init__.py`` call ``load_pybindings(__name__, __path__)`` this assumes that the first entry in list ``__path__`` is where you want the wrapped classes to merge to. """ import imp, sys m = imp.load_dynamic(name, __path__[0] + ".so") thismod = sys.modules[name] for (k,v) in m.__dict__.items(): if not k.startswith("_"): thismod.__dict__[k] = v Wherein you just use the __name__ and __path__ of the current module being imported to locate and load the associated shared library. Then you copy the symbols into the current library. So the call to it in each __init__.py would be: load_pybindings(__name__, __path__) Nice thing is that everything looks quite homogenous to the user. It appears to work quite well, but I just now came up with this and thought I ask if anybody sees any problems. -t From troy at resophonic.com Mon Aug 18 19:41:43 2008 From: troy at resophonic.com (troy d. straszheim) Date: Mon, 18 Aug 2008 13:41:43 -0400 Subject: [C++-sig] Alternate packaging technique for bindings + pure python In-Reply-To: <48A9B063.8070503@resophonic.com> References: <48A9B063.8070503@resophonic.com> Message-ID: <48A9B457.7080707@resophonic.com> troy d. straszheim wrote: > m = imp.load_dynamic(name, __path__[0] + ".so") whoops, that should have been m = imp.load_dynamic(name, path[0] + ".so") sorry for the noise. -t From wladwig at wdtinc.com Mon Aug 18 22:05:37 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Mon, 18 Aug 2008 15:05:37 -0500 Subject: [C++-sig] Overriding c++ abstract class in python Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56A66@storm.wdtinc.com> I'm having problem overriding a c++ abstract class in python (when passing the python object to a c++ function). Here is a really simplified version of my code.: c++ code: class GenericInput { public: virtual void foo(const std::string& filename) = 0; }; void processInput(GenericInput& input, const std::string& filename) { input.foo(filename); } wrapping code: struct GenericInputWrapper : GenericInput, wrapper { this->get_override("foo")(); }; BOOST_PYTHON_MODULE(_core) { class_("GenericInput", no_init) .def("foo", pure_virtual(&GenericInput::foo)) ; def ("processInput", processInput); } python code: import _core class TestInput(_core.GenericInput): def __init__(self): print("init called") def foo(self, filename): print("foo called") >>> A = TestInput() >>> processInput(A, "test") This fails with: Boost.Python.ArgumentError: Python argument types in _core.processInput(TestInput, str) did not match C++ signature: processInput(GenericInput {lvalue}, std::string) However, if I remove the "no_init" from my GenericInput wrapper and also remove the __init__ function from my python TestInput class, I don't get the error. What am I doing wrong here? Thanks. Bill From seefeld at sympatico.ca Mon Aug 18 22:17:33 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Mon, 18 Aug 2008 16:17:33 -0400 Subject: [C++-sig] Overriding c++ abstract class in python In-Reply-To: <765CBD9053EA2B438625895F30D1856FC9E56A66@storm.wdtinc.com> References: <765CBD9053EA2B438625895F30D1856FC9E56A66@storm.wdtinc.com> Message-ID: <48A9D8DD.70506@sympatico.ca> William Ladwig wrote: > python code: > > import _core > class TestInput(_core.GenericInput): > def __init__(self): > print("init called") > Make sure to call the base class' __init__ method explicitely. Python, unlike C++, won't do that for you automatically: class TestInput(_core.GenericInput): def __init__(self): super(TestInput, self).__init__() ... HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From wladwig at wdtinc.com Mon Aug 18 22:50:55 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Mon, 18 Aug 2008 15:50:55 -0500 Subject: [C++-sig] Overriding c++ abstract class in python In-Reply-To: <48A9D8DD.70506@sympatico.ca> References: <765CBD9053EA2B438625895F30D1856FC9E56A66@storm.wdtinc.com> <48A9D8DD.70506@sympatico.ca> Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56A87@storm.wdtinc.com> The base class is abstract in c++ and has no constructor (it will throw an exception if called in python). The problem I am having is more related to how I extract the derived python object properly in a c++ function. If I don't use an __init__ function in the derived python class (and remove the no_init in the c++ wrapper), it happens automatically. However, as soon as I add an __init__ function for the derived class, I get the error: Boost.Python.ArgumentError: Python argument types in _core.processInput(TestInput, str) did not match C++ signature: processInput(GenericInput {lvalue}, std::string) I suspect I need to write a thin wrapper around the processInput() function in order to extract the c++ object from python, but I'm not sure how to do it and preserve the overridden virtual functions. I tried extracting a GenericInputWrapper object, but I get the same error. Any ideas? Bill -----Original Message----- From: c++-sig-bounces+wladwig=wdtinc.com at python.org [mailto:c++-sig-bounces+wladwig=wdtinc.com at python.org] On Behalf Of Stefan Seefeld Sent: Monday, August 18, 2008 3:18 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Overriding c++ abstract class in python William Ladwig wrote: > python code: > > import _core > class TestInput(_core.GenericInput): > def __init__(self): > print("init called") > Make sure to call the base class' __init__ method explicitely. Python, unlike C++, won't do that for you automatically: class TestInput(_core.GenericInput): def __init__(self): super(TestInput, self).__init__() ... 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 From wladwig at wdtinc.com Tue Aug 19 00:30:14 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Mon, 18 Aug 2008 17:30:14 -0500 Subject: [C++-sig] Overriding c++ abstract class in python In-Reply-To: <765CBD9053EA2B438625895F30D1856FC9E56A87@storm.wdtinc.com> References: <765CBD9053EA2B438625895F30D1856FC9E56A66@storm.wdtinc.com> <48A9D8DD.70506@sympatico.ca> <765CBD9053EA2B438625895F30D1856FC9E56A87@storm.wdtinc.com> Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56ACC@storm.wdtinc.com> Correction: If I try to extract a reference to the GenericInputWrapper, I get: TypeError: No registered converter was able to extract a C++ reference to type GenericInputWrapper from this Python object of type TestInput Is this description on the boost python Wiki page the correct way to handle this situation or is it out of date? http://wiki.python.org/moin/boost.python/HowTo#head-5665b70c155b2eb814a3d39898d9b9fae04c3dc3 Thanks. Bill -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of William Ladwig Sent: Monday, August 18, 2008 3:51 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Overriding c++ abstract class in python The base class is abstract in c++ and has no constructor (it will throw an exception if called in python). The problem I am having is more related to how I extract the derived python object properly in a c++ function. If I don't use an __init__ function in the derived python class (and remove the no_init in the c++ wrapper), it happens automatically. However, as soon as I add an __init__ function for the derived class, I get the error: Boost.Python.ArgumentError: Python argument types in _core.processInput(TestInput, str) did not match C++ signature: processInput(GenericInput {lvalue}, std::string) I suspect I need to write a thin wrapper around the processInput() function in order to extract the c++ object from python, but I'm not sure how to do it and preserve the overridden virtual functions. I tried extracting a GenericInputWrapper object, but I get the same error. Any ideas? Bill -----Original Message----- From: c++-sig-bounces+wladwig=wdtinc.com at python.org [mailto:c++-sig-bounces+wladwig=wdtinc.com at python.org] On Behalf Of Stefan Seefeld Sent: Monday, August 18, 2008 3:18 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Overriding c++ abstract class in python William Ladwig wrote: > python code: > > import _core > class TestInput(_core.GenericInput): > def __init__(self): > print("init called") > Make sure to call the base class' __init__ method explicitely. Python, unlike C++, won't do that for you automatically: class TestInput(_core.GenericInput): def __init__(self): super(TestInput, self).__init__() ... 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 _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig From greg.landrum at gmail.com Tue Aug 19 07:07:22 2008 From: greg.landrum at gmail.com (Greg Landrum) Date: Tue, 19 Aug 2008 07:07:22 +0200 Subject: [C++-sig] Accessing python configuration data when building extensions using bjam and boost.python Message-ID: <60825b0f0808182207k62f65c5aq1771aafb9d412836@mail.gmail.com> Dear all, I've recently switched the code for one of my projects from Numeric to numpy. The project includes a number of extension modules built using boost.python. So far everything seems to work without problems except for building the modules in a "pleasant" way. Here's the problem: Numeric python would, by default, install itself in such a way that its header files were in a subdirectory of the python include directory. So things like "#include " would work without any special handling in extension files built using bjam. Numpy, on the other hand, installs its header files with its Python files in site-packages. So I need to add something like this to my Jamroot : gcc:/usr/lib/python2.5/site-packages/numpy/core/include This is, obviously, dependent on operating system, python version and python installation-location. So the user will have to edit the Jamroot based on their details. One of the things I really like about boost.build is that this kind of stuff is normally not required. I could solve this problem, I think, there were a variable (?) in python.jam defining the location of python's "lib" directory that I could access from my Jamroot. Then I could have something like: $(python-lib-dir)/numpy/core/include that would work on every machine. I've spent some time looking through the boost.build documentation and python.jam, but I was unable to figure out how to expose a new variable that would be accessible from other Jamfiles. Does anyone have a recipe for doing this? Thanks, -greg From roman.yakovenko at gmail.com Tue Aug 19 08:30:57 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 19 Aug 2008 09:30:57 +0300 Subject: [C++-sig] Overriding c++ abstract class in python In-Reply-To: <765CBD9053EA2B438625895F30D1856FC9E56ACC@storm.wdtinc.com> References: <765CBD9053EA2B438625895F30D1856FC9E56A66@storm.wdtinc.com> <48A9D8DD.70506@sympatico.ca> <765CBD9053EA2B438625895F30D1856FC9E56A87@storm.wdtinc.com> <765CBD9053EA2B438625895F30D1856FC9E56ACC@storm.wdtinc.com> Message-ID: <7465b6170808182330t40f7f10du4bbf0d8ca9574339@mail.gmail.com> On Tue, Aug 19, 2008 at 1:30 AM, William Ladwig wrote: > Correction: If I try to extract a reference to the GenericInputWrapper, I get: > > TypeError: No registered converter was able to extract a C++ reference to type GenericInputWrapper from this Python object of type TestInput > > Is this description on the boost python Wiki page the correct way to handle this situation or is it out of date? > > http://wiki.python.org/moin/boost.python/HowTo#head-5665b70c155b2eb814a3d39898d9b9fae04c3dc3 The code you build for your classes is incorrect. GenericInput class do have default constructor. Next code was generated by Py++, for GenericInput class struct GenericInput_wrapper : GenericInput, bp::wrapper< GenericInput > { GenericInput_wrapper() : GenericInput() , bp::wrapper< GenericInput >(){ // null constructor } virtual void foo( ::std::string const & filename ){ bp::override func_foo = this->get_override( "foo" ); func_foo( filename ); } }; BOOST_PYTHON_MODULE(pyplusplus){ bp::class_< GenericInput_wrapper, boost::noncopyable >( "GenericInput" ) .def( "foo" , bp::pure_virtual( (void ( ::GenericInput::* )( ::std::string const & ) )(&::GenericInput::foo) ) , ( bp::arg("filename") ) ); } -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From meine at informatik.uni-hamburg.de Tue Aug 19 10:42:39 2008 From: meine at informatik.uni-hamburg.de (Hans Meine) Date: Tue, 19 Aug 2008 10:42:39 +0200 Subject: [C++-sig] Alternate packaging technique for bindings + pure python In-Reply-To: <48A9B063.8070503@resophonic.com> References: <48A9B063.8070503@resophonic.com> Message-ID: <200808191042.40134.meine@informatik.uni-hamburg.de> On Monday 18 August 2008 19:24:51 troy d. straszheim wrote: > If you organize things like this, instead: > > core.so > core/ > __init__.py > foo.py > bar.py > > You can use the following function: [...] > > Nice thing is that everything looks quite homogenous to the user. It > appears to work quite well, but I just now came up with this and thought I > ask if anybody sees any problems. I would check with pickle, ipython, epydoc, sphinx, etc. whether your approach makes any problems. (The documentation tools probably have ways to work around the underscores etc.) Also, not everybody might want to rely on imp, __name__, and __path__. Otherwise, it looks like a neat trick to me. Nice greetings, Hans From paul.bilokon at lehman.com Tue Aug 19 15:10:23 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Tue, 19 Aug 2008 14:10:23 +0100 Subject: [C++-sig] Static and non-static functions with the same name Message-ID: Hi, In C++ it's possible to have the following situation: class Foo { public: string garply(int x, int y) { return "I am the non-static Foo::garply(int, int)"; } static string garply(string z) { return "I am the static Foo::garly(string)"; } }; Now I want to expose both the static and non-static garply to Python, and here I'm stuck: using namespace boost::python; BOOST_PYTHON_MODULE(overloading) { class_("Foo") .def("garply", (string (*)(string)) &Foo::garply) .def("garply", (string (Foo::*)(int, int)) &Foo::garply) .staticmethod("garply") // ??? Which garply is that ??? ; } staticmethod takes a single string as its parameter, the function name. But I have both static and non-static variants. How do I specify which of them is static? [Technically it's possible. We already differentiate between overloaded functions on the Python side, so we just need to check if the first argument is "self", e.g. by looking at its type -- hardly foolproof though, e.g. consider a "copy-constructor" signature...] Of course, one may ask why don't I give the Python functions different names. But what if I'm trying to replicate the C++ API as faithfully as I can? I would like to avoid name changes. What's the best thing to do? Many thanks! Regards, Paul - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From lists_ravi at lavabit.com Tue Aug 19 16:52:35 2008 From: lists_ravi at lavabit.com (Ravi) Date: Tue, 19 Aug 2008 10:52:35 -0400 Subject: [C++-sig] Static and non-static functions with the same name In-Reply-To: References: Message-ID: <200808191052.36559.lists_ravi@lavabit.com> On Tuesday 19 August 2008 09:10:23 Bilokon, Paul wrote: > using namespace boost::python; > > BOOST_PYTHON_MODULE(overloading) > { > ? ? class_("Foo") > ? ? ? ? .def("garply", (string (*)(string)) &Foo::garply) > ? ? ? ? .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > ? ? ? ? .staticmethod("garply") > ? ? ? ? ? ? // ??? Which garply is that ??? > ? ? ; > } Try an extra level of indirection: using namespace boost::python; string foo_pygarply( string z ) { return Foo::garply(z); } BOOST_PYTHON_MODULE(overloading) { ? ? class_("Foo") ? ? ? ? .def("garply", (string (*)(string)) &Foo::garply) ? ? ? ? .def("garply", (string (Foo::*)(int, int)) &Foo::garply) ? ? ? ? .staticmethod("foo_pygarply") ? ? ; } Regards, Ravi -------------- next part -------------- An HTML attachment was scrubbed... URL: From wladwig at wdtinc.com Tue Aug 19 16:54:40 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Tue, 19 Aug 2008 09:54:40 -0500 Subject: [C++-sig] Overriding c++ abstract class in python In-Reply-To: <7465b6170808182330t40f7f10du4bbf0d8ca9574339@mail.gmail.com> References: <765CBD9053EA2B438625895F30D1856FC9E56A66@storm.wdtinc.com> <48A9D8DD.70506@sympatico.ca> <765CBD9053EA2B438625895F30D1856FC9E56A87@storm.wdtinc.com> <765CBD9053EA2B438625895F30D1856FC9E56ACC@storm.wdtinc.com> <7465b6170808182330t40f7f10du4bbf0d8ca9574339@mail.gmail.com> Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56B20@storm.wdtinc.com> Thanks for your help! I was actually going to play around with Py++ to see what it came up with, but haven't had a chance yet to try it. Now I see where I messed up. My c++ base class is abstract, but the wrapper around it is not, so I probably don't want to be using "no_init" when I create the bp::class_ definition. From nickm at sitius.com Tue Aug 19 19:08:32 2008 From: nickm at sitius.com (Nikolay Mladenov) Date: Tue, 19 Aug 2008 13:08:32 -0400 Subject: [C++-sig] Static and non-static functions with the same name In-Reply-To: References: Message-ID: Please remind me, what happens if you do not put .staticmethod("garply"), and then try : >>> Foo().garply(0,0) >>> Foo.garply("") ? > class_("Foo") > .def("garply", (string (*)(string)) &Foo::garply) > .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > .staticmethod("garply") Bilokon, Paul wrote: > Hi, > > In C++ it's possible to have the following situation: > > class Foo > { > public: > > string garply(int x, int y) > { > return "I am the non-static Foo::garply(int, int)"; > } > > static string garply(string z) > { > return "I am the static Foo::garly(string)"; > } > }; > > Now I want to expose both the static and non-static garply to Python, > and here I'm stuck: > > using namespace boost::python; > > BOOST_PYTHON_MODULE(overloading) > { > class_("Foo") > .def("garply", (string (*)(string)) &Foo::garply) > .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > .staticmethod("garply") > // ??? Which garply is that ??? > ; > } > > staticmethod takes a single string as its parameter, the function name. > But I have both static and non-static variants. How do I specify which > of them is static? [Technically it's possible. We already differentiate > between overloaded functions on the Python side, so we just need to > check if the first argument is "self", e.g. by looking at its type -- > hardly foolproof though, e.g. consider a "copy-constructor" > signature...] > > Of course, one may ask why don't I give the Python functions different > names. But what if I'm trying to replicate the C++ API as faithfully as > I can? I would like to avoid name changes. > > What's the best thing to do? > > Many thanks! > > Regards, > Paul > > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > > This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From wladwig at wdtinc.com Tue Aug 19 21:16:08 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Tue, 19 Aug 2008 14:16:08 -0500 Subject: [C++-sig] Extracting and returning a c++ object from python and garbage collection Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> I'm having a problem overriding a pure C++ virtual function in python which returns an auto_ptr to a C++ type (which has been exposed to python). It looks like I am extracting the class correctly in my base class wrapper, but when the function returns to python, it throws a segmentation fault if I try to access the returned object. I suspect I have a garbage collection problem, but I'm not sure what I'm doing wrong. How do I convert an object from python to C++ and return the C++ object without it being garbage collected? Here is a sample to illustrate the problem: C++ code: using namespace boost::python; // Generic Input abstract base class class GenericInput { public: // Pure virtual function to convert to the required type std::auto_ptr void convToReqFormat() = 0; }; // Required input format class ReqInput { public: ReqInput(unsigned int rows, unsigned int cols) : _Rows(rows), _Cols(cols) unsigned int getRows() const {return _Rows;} unsigned int getCols() const {return _Cols;} private: unsigned int _Rows; unsigned int _Cols; }; // Function which converts GenericInput to ReqInput std::auto_ptr processInput(GenericInput& input) { return input.convToReqFormat(); } boost python wrapping code: struct GenericInputWrapper : GenericInput, wrapper { GenericInputWrapper() : GenericInput(), wrapper() {} // ********** Here is where my problem is ********************* std::auto_ptr void convToReqFormat() { // This will return a python object of the exposed ReqInput type override func = this->get_override("convToReqFormat"); object py_obj = func(); ReqInput& req_in = extract(py_obj); // Testing extraction std::cout << "Testing extraction: " << req_in.getRows(); std::cout << "," << req_in.getCols() << std::endl; // Store in an auto_ptr std::auto_ptr r; r.reset(&req_in); return r; }; BOOST_PYTHON_MODULE(_core) { class_("ReqInput", init) .add_property("Rows", &ReqInput::getRows) .add_property("Cols", &ReqInput::getCols) class_("GenericInput", no_init) .def("foo", pure_virtual(&GenericInput::foo)) ; def ("processInput", processInput); } Python test code: import _core class TestInput(_core.GenericInput): def __init__(self, rows, cols): _core.GenericInput.__init__(self) self.Rows = rows self.Cols = cols def convToReqFormat(self): return ReqInput(10,10) >>> A = TestInput(10,10) >>> B = processInput(A) Testing extraction: 10,10 >>> B.Rows Segmentation Fault Thank you for your help, Bill From roman.yakovenko at gmail.com Tue Aug 19 21:39:39 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 19 Aug 2008 22:39:39 +0300 Subject: [C++-sig] Extracting and returning a c++ object from python and garbage collection In-Reply-To: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> References: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> Message-ID: <7465b6170808191239w28719f5bra5f40eea0e5ec5f4@mail.gmail.com> On Tue, Aug 19, 2008 at 10:16 PM, William Ladwig wrote: > > > I'm having a problem overriding a pure C++ virtual function in python which returns an auto_ptr to a C++ type (which has been exposed to python). It looks like I am extracting the class correctly in my base class wrapper, but when the function returns to python, it throws a segmentation fault if I try to access the returned object. I suspect I have a garbage collection problem, but I'm not sure what I'm doing wrong. How do I convert an object from python to C++ and return the C++ object without it being garbage collected? Here is a sample to illustrate the problem: > > C++ code: > ... > // ********** Here is where my problem is ********************* > std::auto_ptr void convToReqFormat() > { > // This will return a python object of the exposed ReqInput type > override func = this->get_override("convToReqFormat"); > object py_obj = func(); > > ReqInput& req_in = extract(py_obj); > std::auto_ptr r; > r.reset(&req_in); At some point you have same pointer, managed by 2 objects. Also why do you need to write such code? I attach the code, generated by Py++. I am pretty sure it will work as-is. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- A non-text attachment was scrubbed... Name: 1.h Type: text/x-chdr Size: 2753 bytes Desc: not available URL: From wladwig at wdtinc.com Tue Aug 19 22:13:08 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Tue, 19 Aug 2008 15:13:08 -0500 Subject: [C++-sig] Extracting and returning a c++ object from python and garbage collection In-Reply-To: <7465b6170808191239w28719f5bra5f40eea0e5ec5f4@mail.gmail.com> References: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> <7465b6170808191239w28719f5bra5f40eea0e5ec5f4@mail.gmail.com> Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56BDE@storm.wdtinc.com> My actual code is a little different than what is posted here, but the basic idea is that we use many different input formats that are similar (all represent "2D" arrays of data), but need to be converted to a common "2D" array format before being processed. For this, I am using an abstract base class where one of the virtual functions handles the conversion and returns an auto_ptr to the required input type. This is easy to do in C++, but if I want to override that virtual function in python, I'm not quite sure how to return an auto_ptr to a C++ object. (I'm trying to allow for the development of the input portion of the application to be done in either c++ or python). When I initially tried to do this, I wrapped the GenericInput class as: struct GenericInputWrapper : GenericInput, wrapper { GenericInputWrapper() : GenericInput(), wrapper() {} std::auto_ptr void convToReqFormat() { std::auto_ptr r; r.reset(this->get_override("convToReqFormat")); return r; } }; However, this threw the "dangling reference" error. So, I figured I needed to extract the python object first, and then convert it to an auto_ptr. -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Roman Yakovenko Sent: Tuesday, August 19, 2008 2:40 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Extracting and returning a c++ object from python and garbage collection On Tue, Aug 19, 2008 at 10:16 PM, William Ladwig wrote: > > > I'm having a problem overriding a pure C++ virtual function in python which returns an auto_ptr to a C++ type (which has been exposed to python). It looks like I am extracting the class correctly in my base class wrapper, but when the function returns to python, it throws a segmentation fault if I try to access the returned object. I suspect I have a garbage collection problem, but I'm not sure what I'm doing wrong. How do I convert an object from python to C++ and return the C++ object without it being garbage collected? Here is a sample to illustrate the problem: > > C++ code: > ... > // ********** Here is where my problem is ********************* > std::auto_ptr void convToReqFormat() > { > // This will return a python object of the exposed ReqInput type > override func = this->get_override("convToReqFormat"); > object py_obj = func(); > > ReqInput& req_in = extract(py_obj); > std::auto_ptr r; > r.reset(&req_in); At some point you have same pointer, managed by 2 objects. Also why do you need to write such code? I attach the code, generated by Py++. I am pretty sure it will work as-is. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From wladwig at wdtinc.com Wed Aug 20 00:03:03 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Tue, 19 Aug 2008 17:03:03 -0500 Subject: [C++-sig] Extracting and returning a c++ object from python and garbage collection In-Reply-To: <765CBD9053EA2B438625895F30D1856FC9E56BDE@storm.wdtinc.com> References: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> <7465b6170808191239w28719f5bra5f40eea0e5ec5f4@mail.gmail.com> <765CBD9053EA2B438625895F30D1856FC9E56BDE@storm.wdtinc.com> Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56C1C@storm.wdtinc.com> I looked at the Py++ code and tried it out (it's similar to how I tried it originally) and it also throws a "dangling pointer" exception from the interpreter. I was able to keep it from crashing by extracting a ReqInput reference and then creating a new ReqInput by copying the extracted one. It's not very efficient unfortunately, but it might be the only way to do this. Thanks again for your help. std::auto_ptr convToReqInput() { object py_ob = this->get_override("toMapleInputArray")(); ReqInput& r_arr = extract(py_ob); std::auto_ptr r(new ReqInput(r_arr)); return r; } Bill From dave at boostpro.com Wed Aug 20 04:35:41 2008 From: dave at boostpro.com (David Abrahams) Date: Tue, 19 Aug 2008 18:35:41 -0800 Subject: [C++-sig] How to wrap a python function pointer ? In-Reply-To: <19028640.post@talk.nabble.com> ("William =?utf-8?Q?Mari?= =?utf-8?Q?=C3=A9=22's?= message of "Mon, 18 Aug 2008 03:01:48 -0700 (PDT)") References: <19028640.post@talk.nabble.com> Message-ID: <87hc9g4dmq.fsf@mcbain.luannocracy.com> on Mon Aug 18 2008, William Mari? wrote: > I would like to wrap a python function pointer to a void (*c++fun)() pointer > : > > typedef void (*fct_void_void)( void ); > void addTimer( double dStartIn, double dTickTime, u32 iTickCount, > fct_void_void bpFctCallback ) > { > ..... > > } > BOOST_PYTHON_MODULE(ksys) > { > using namespace boost::python; > def("addTimer", &addTimer); > } Hi, Sorry, but right now we don't have a good solution for that use case. The best I can offer immediately is that you define a small struct that holds a fct_void_void, expose that to Python as usual, and then create a thin wrapper for addTimer that takes the struct instead of the function pointer. This could be fixed, though. Would you care to open a trac ticket at http://svn.boost.org -- Dave Abrahams BoostPro Computing http://www.boostpro.com From william.marie at gmail.com Wed Aug 20 09:37:27 2008 From: william.marie at gmail.com (=?ISO-8859-1?Q?william_mari=E9?=) Date: Wed, 20 Aug 2008 08:37:27 +0100 Subject: [C++-sig] How to wrap a python function pointer ? In-Reply-To: <87hc9g4dmq.fsf@mcbain.luannocracy.com> References: <19028640.post@talk.nabble.com> <87hc9g4dmq.fsf@mcbain.luannocracy.com> Message-ID: <168485c00808200037t2ad3a1cav4d097090e5289d4@mail.gmail.com> Hi, Ok ticket created : http://svn.boost.org/trac/boost/ticket/2230 Thanks bye William 2008/8/20 David Abrahams > > on Mon Aug 18 2008, William Mari? wrote: > > > I would like to wrap a python function pointer to a void (*c++fun)() > pointer > > : > > > > typedef void (*fct_void_void)( void ); > > void addTimer( double dStartIn, double dTickTime, u32 iTickCount, > > fct_void_void bpFctCallback ) > > { > > ..... > > > > } > > BOOST_PYTHON_MODULE(ksys) > > { > > using namespace boost::python; > > def("addTimer", &addTimer); > > } > > Hi, > > Sorry, but right now we don't have a good solution for that use case. > The best I can offer immediately is that you define a small struct that > holds a fct_void_void, expose that to Python as usual, and then create a > thin wrapper for addTimer that takes the struct instead of the function > pointer. > > This could be fixed, though. Would you care to open a trac ticket at > http://svn.boost.org > > > -- > Dave Abrahams > BoostPro Computing > http://www.boostpro.com > _______________________________________________ > 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 paul.bilokon at lehman.com Wed Aug 20 10:32:56 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Wed, 20 Aug 2008 09:32:56 +0100 Subject: [C++-sig] Static and non-static functions with the same name In-Reply-To: References: Message-ID: Hi Nikolay, This is what you get. Say you have .def("staticGarply", (string (*)(string)) &Foo::garply) And you comment out... // .staticmethod("staticGarply") In Python, I attempt the following: print Foo.staticGarply('yo') And get... TypeError: unbound method Boost.Python.function object must be called with Foo instance as first argument (got str instance instead) Regards, Paul -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Nikolay Mladenov Sent: Tuesday, August 19, 2008 6:09 PM To: c++-sig at python.org Subject: Re: [C++-sig] Static and non-static functions with the same name Please remind me, what happens if you do not put .staticmethod("garply"), and then try : >>> Foo().garply(0,0) >>> Foo.garply("") ? > class_("Foo") > .def("garply", (string (*)(string)) &Foo::garply) > .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > .staticmethod("garply") Bilokon, Paul wrote: > Hi, > > In C++ it's possible to have the following situation: > > class Foo > { > public: > > string garply(int x, int y) > { > return "I am the non-static Foo::garply(int, int)"; > } > > static string garply(string z) > { > return "I am the static Foo::garly(string)"; > } > }; > > Now I want to expose both the static and non-static garply to Python, > and here I'm stuck: > > using namespace boost::python; > > BOOST_PYTHON_MODULE(overloading) > { > class_("Foo") > .def("garply", (string (*)(string)) &Foo::garply) > .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > .staticmethod("garply") > // ??? Which garply is that ??? > ; > } > > staticmethod takes a single string as its parameter, the function name. > But I have both static and non-static variants. How do I specify which > of them is static? [Technically it's possible. We already > differentiate between overloaded functions on the Python side, so we > just need to check if the first argument is "self", e.g. by looking at > its type -- hardly foolproof though, e.g. consider a "copy-constructor" > signature...] > > Of course, one may ask why don't I give the Python functions different > names. But what if I'm trying to replicate the C++ API as faithfully > as I can? I would like to avoid name changes. > > What's the best thing to do? > > Many thanks! > > Regards, > Paul > > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > - - - - - - - - - > > This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From paul.bilokon at lehman.com Wed Aug 20 10:40:04 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Wed, 20 Aug 2008 09:40:04 +0100 Subject: [C++-sig] Static and non-static functions with the same name In-Reply-To: <200808191052.36559.lists_ravi@lavabit.com> References: <200808191052.36559.lists_ravi@lavabit.com> Message-ID: Hi Ravi, If my understanding is correct, this method has the same deficiency as simply doing this: // OK, explicitly specifying the static garply(string): .def("staticGarply", (string (*)(string)) &Foo::garply) .staticmethod("staticGarply") // OK, explicitly specifying the non-static garply(int, int): .def("garply", (string (Foo::*)(int, int)) &Foo::garply) // NB: The syntax: (*) for static, (Foo::*) for non-static // NB: Since staticmethod does not distinguish between the method // signatures, we must give the static and non-static variants // distinct names in Python This works, but the static and non-static variants end up having different names on the Python side. Kind regards, Paul ________________________________ From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Ravi Sent: Tuesday, August 19, 2008 3:53 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Static and non-static functions with the same name On Tuesday 19 August 2008 09:10:23 Bilokon, Paul wrote: > using namespace boost::python; > > BOOST_PYTHON_MODULE(overloading) > { > class_("Foo") > .def("garply", (string (*)(string)) &Foo::garply) > .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > .staticmethod("garply") > // ??? Which garply is that ??? > ; > } Try an extra level of indirection: using namespace boost::python; string foo_pygarply( string z ) { return Foo::garply(z); } BOOST_PYTHON_MODULE(overloading) { class_("Foo") .def("garply", (string (*)(string)) &Foo::garply) .def("garply", (string (Foo::*)(int, int)) &Foo::garply) .staticmethod("foo_pygarply") ; } Regards, Ravi - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivanov.maxim at gmail.com Wed Aug 20 20:13:13 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Wed, 20 Aug 2008 22:13:13 +0400 Subject: [C++-sig] copy_const_reference on add_property Message-ID: Hi all! If C++ method returns std::strings I'm forced to add "return_value_policy()" as third argument to "def". How to make similair for add_property? From roman.yakovenko at gmail.com Wed Aug 20 20:18:15 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 20 Aug 2008 21:18:15 +0300 Subject: [C++-sig] Extracting and returning a c++ object from python and garbage collection In-Reply-To: <765CBD9053EA2B438625895F30D1856FC9E56C1C@storm.wdtinc.com> References: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> <7465b6170808191239w28719f5bra5f40eea0e5ec5f4@mail.gmail.com> <765CBD9053EA2B438625895F30D1856FC9E56BDE@storm.wdtinc.com> <765CBD9053EA2B438625895F30D1856FC9E56C1C@storm.wdtinc.com> Message-ID: <7465b6170808201118j1f6dd0b8q78741d8f7b8c627@mail.gmail.com> On Wed, Aug 20, 2008 at 1:03 AM, William Ladwig wrote: > I looked at the Py++ code and tried it out (it's similar to how I tried it originally) and it also throws a "dangling pointer" exception from the interpreter. Interesting, I've got other errors. Using Visual Studio 2003, I got warning during compilation and TypeError during runtime, which says, that Boost.Python is not able to construct rvalue, std::auto_ptr< your class >, from the Python object. Using gcc 4.2.3, on Ubuntu the generated code didn't compiled and when I fixed it, than everything was fine and worked as expected I attached source code, "fixed" generated code and small tester. What is your environment? Any way, it seems that I found solution. The only change was to extract std::auto_ptr<> as is, by value, from Python object. Let me know, if this really solves your problem, I will fix Py++. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- A non-text attachment was scrubbed... Name: return_auto_ptr_to_be_exported.hpp Type: text/x-csrc Size: 1265 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: return_auto_ptr.cpp Type: text/x-c++src Size: 3964 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: x.py Type: text/x-python Size: 573 bytes Desc: not available URL: From roman.yakovenko at gmail.com Wed Aug 20 20:22:50 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 20 Aug 2008 21:22:50 +0300 Subject: [C++-sig] copy_const_reference on add_property In-Reply-To: References: Message-ID: <7465b6170808201122x72a9710ev59d7232278beafdb@mail.gmail.com> On Wed, Aug 20, 2008 at 9:13 PM, Max Ivanov wrote: > Hi all! > If C++ method returns std::strings I'm forced to add > "return_value_policy()" as third argument to > "def". How to make similair for add_property? You should use boost::python::make_function namespace bp = boost::python; .add_property( "name" , bp::make_function( , ) ); HTH -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From wladwig at wdtinc.com Wed Aug 20 21:11:25 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Wed, 20 Aug 2008 14:11:25 -0500 Subject: [C++-sig] Extracting and returning a c++ object from python and garbage collection In-Reply-To: <7465b6170808201118j1f6dd0b8q78741d8f7b8c627@mail.gmail.com> References: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> <7465b6170808191239w28719f5bra5f40eea0e5ec5f4@mail.gmail.com> <765CBD9053EA2B438625895F30D1856FC9E56BDE@storm.wdtinc.com> <765CBD9053EA2B438625895F30D1856FC9E56C1C@storm.wdtinc.com> <7465b6170808201118j1f6dd0b8q78741d8f7b8c627@mail.gmail.com> Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56D3B@storm.wdtinc.com> I am using an older version of gcc (3.4.6) on Redhat Linux. My python interpreter is v2.5.2 Upon doing some digging using google, I found this thread where the poster is doing something very similar to what I am trying to do: http://mail.python.org/pipermail/c++-sig/2005-May/008867.html The compiling errors are due to the way the auto_ptr is defined in the STL. I don't think the suggested fix in the thread compiled for me either due to "ambiguous" overloaded function errors. So, I ended up using (before I posted my thread yesterday): std::auto_ptr void convToReqFormat() { std::auto_ptr r; r.reset(this->get_override("convToReqInput")()); return r; } This code will compile, but if I try to use the returned object, it crashes with a segmentation fault, which I suspect is because the python exposed "c++" object returned by this->get_override() is being garbage collected when the wrapper function returns. One solution that fixed the problem for me was to extract to the ReqInput object, then create a new ReqInput object which copies the extracted object, and returns an auto_ptr to the new object. std::auto_ptr void convToReqFormat() { object py_input = this->get_override("convToReqInput")(); ReqInput& r_in = extract(py_arr); std::auto_ptr r(new ReqInput(r_in)); return r; } This is horribly inefficient (considering the object contained in my real code contains a 6000x6000 array), but doesn't crash on me. I never tried extracting an auto_ptr directly however, which is probably what I should have been doing all along, since that is the object that the virtual function is returning. I'll give it a try and see how it works out. Thanks! -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Roman Yakovenko Sent: Wednesday, August 20, 2008 1:18 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] Extracting and returning a c++ object from python and garbage collection On Wed, Aug 20, 2008 at 1:03 AM, William Ladwig wrote: > I looked at the Py++ code and tried it out (it's similar to how I tried it originally) and it also throws a "dangling pointer" exception from the interpreter. Interesting, I've got other errors. Using Visual Studio 2003, I got warning during compilation and TypeError during runtime, which says, that Boost.Python is not able to construct rvalue, std::auto_ptr< your class >, from the Python object. Using gcc 4.2.3, on Ubuntu the generated code didn't compiled and when I fixed it, than everything was fine and worked as expected I attached source code, "fixed" generated code and small tester. What is your environment? Any way, it seems that I found solution. The only change was to extract std::auto_ptr<> as is, by value, from Python object. Let me know, if this really solves your problem, I will fix Py++. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From ope-devel at gmx.de Wed Aug 20 21:27:48 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Wed, 20 Aug 2008 21:27:48 +0200 Subject: [C++-sig] [pybindgen] Problems on PyObject* param Message-ID: <48AC7034.8080802@gmx.de> Hi, I try out some binding generator tools and start with pybindgen :) Anyway, here my script: import pybindgen import sys # convinience param=pybindgen.param retval=pybindgen.retval mod = pybindgen.Module('redirector') mod.add_include('"redirector.hpp"') stdout_py = mod.add_class('StdoutPy') stdout_py.add_constructor([]) stdout_py.add_method('write', None, [param('PyObject*', 'value')]) stdout_py.add_method('flush', None, []) stderr_py = mod.add_class('StderrPy') stderr_py.add_constructor([]) stderr_py.add_method('write', None, [param('PyObject*', 'value')]) stderr_py.add_method('flush', None, []) stdin_py = mod.add_class('StdinPy') stdin_py.add_constructor([]) stdin_py.add_method('readline', retval('PyObject*'), [param('PyObject*', 'value')]) mod.generate(sys.stdout) for this classes: class PyConsole; class StdoutPy : public boost::noncopyable { public: StdoutPy(PyConsole* console); void write(PyObject* args); void flush(); private: PyConsole* m_console; }; class StderrPy : public boost::noncopyable { public: StderrPy(PyObject* console); void write(PyObject* args); void flush(); private: PyConsole* m_console; }; class StdinPy : public boost::noncopyable { public: StdinPy(PyConsole* console); PyObject* readline(PyObject* args); private: PyConsole* m_console; }; as you assume, topic is redirection of the sys write function to a gui. Anyway, I've got errors. Any help? $ python redirector.py /usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py:1173: UserWarning: Exception '__init__() takes at least 4 arguments (3 given)' in type handler constructor warnings.warn("Exception %r in type handler %s constructor" % (str(ex), type_handler_class)) Traceback (most recent call last): File "redirector.py", line 13, in stdout_py.add_method('write', None, [param('PyObject*', 'value')]) File "/usr/lib/python2.5/site-packages/pybindgen/cppclass.py", line 1127, in add_method meth = CppMethod(*args, **kwargs) File "/usr/lib/python2.5/site-packages/pybindgen/cppmethod.py", line 104, in __init__ parameters = [utils.eval_param(param, self) for param in parameters] File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 205, in eval_param TypeLookupError)) File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 115, in call_with_error_handling return callable(*args, **kwargs) File "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line 1171, in new return type_handler_class(*args, **kwargs) TypeError: __init__() takes at least 4 arguments (3 given) The idea is to create the object in C++ and then set it to python, inside PyConsole class like: stdoutPy = new StdoutPy(this); ... PySys_SetObject("stdout", stdoutPy); and the redirect the member calls from python into C++. Thanks, Olaf From wladwig at wdtinc.com Wed Aug 20 22:32:43 2008 From: wladwig at wdtinc.com (William Ladwig) Date: Wed, 20 Aug 2008 15:32:43 -0500 Subject: [C++-sig] Extracting and returning a c++ object from python and garbage collection In-Reply-To: <7465b6170808201118j1f6dd0b8q78741d8f7b8c627@mail.gmail.com> References: <765CBD9053EA2B438625895F30D1856FC9E56BAF@storm.wdtinc.com> <7465b6170808191239w28719f5bra5f40eea0e5ec5f4@mail.gmail.com> <765CBD9053EA2B438625895F30D1856FC9E56BDE@storm.wdtinc.com> <765CBD9053EA2B438625895F30D1856FC9E56C1C@storm.wdtinc.com> <7465b6170808201118j1f6dd0b8q78741d8f7b8c627@mail.gmail.com> Message-ID: <765CBD9053EA2B438625895F30D1856FC9E56D76@storm.wdtinc.com> Woohoo! It worked. It turns out that I also forgot to hold the ReqInput in an auto_ptr in the ReqInput "class_" wrapper definition (along with extracting the auto_ptr object by value in the virtual function wrapper). All of this is being done correctly by your Py++ code, so I think your Py++ change is ready for use. Thanks for your help! From gjcarneiro at gmail.com Wed Aug 20 22:41:21 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Wed, 20 Aug 2008 21:41:21 +0100 Subject: [C++-sig] [pybindgen] Problems on PyObject* param In-Reply-To: <48AC7034.8080802@gmx.de> References: <48AC7034.8080802@gmx.de> Message-ID: 2008/8/20 Olaf Peter > Hi, > > I try out some binding generator tools and start with pybindgen :) > > Anyway, here my script: > > > import pybindgen > import sys > > # convinience > param=pybindgen.param > retval=pybindgen.retval > > mod = pybindgen.Module('redirector') > mod.add_include('"redirector.hpp"') > > stdout_py = mod.add_class('StdoutPy') > stdout_py.add_constructor([]) > stdout_py.add_method('write', None, [param('PyObject*', 'value')]) > stdout_py.add_method('flush', None, []) > > stderr_py = mod.add_class('StderrPy') > stderr_py.add_constructor([]) > stderr_py.add_method('write', None, [param('PyObject*', 'value')]) > stderr_py.add_method('flush', None, []) > > stdin_py = mod.add_class('StdinPy') > stdin_py.add_constructor([]) > stdin_py.add_method('readline', retval('PyObject*'), [param('PyObject*', > 'value')]) > > mod.generate(sys.stdout) > > for this classes: > > class PyConsole; > > class StdoutPy > : public boost::noncopyable > { > public: > StdoutPy(PyConsole* console); > void write(PyObject* args); > void flush(); > private: > PyConsole* m_console; > }; > > > class StderrPy > : public boost::noncopyable > { > public: > StderrPy(PyObject* console); > void write(PyObject* args); > void flush(); > private: > PyConsole* m_console; > }; > > > class StdinPy > : public boost::noncopyable > { > public: > StdinPy(PyConsole* console); > PyObject* readline(PyObject* args); > private: > PyConsole* m_console; > }; > > as you assume, topic is redirection of the sys write function to a gui. > Anyway, I've got errors. Any help? > > $ python redirector.py > /usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py:1173: > UserWarning: Exception '__init__() takes at least 4 arguments (3 given)' > in type handler 'pybindgen.typehandlers.pyobjecttype.PyObjectParam'> constructor > warnings.warn("Exception %r in type handler %s constructor" % > (str(ex), type_handler_class)) > Traceback (most recent call last): > File "redirector.py", line 13, in > stdout_py.add_method('write', None, [param('PyObject*', 'value')]) > File "/usr/lib/python2.5/site-packages/pybindgen/cppclass.py", line > 1127, in add_method > meth = CppMethod(*args, **kwargs) > File "/usr/lib/python2.5/site-packages/pybindgen/cppmethod.py", line > 104, in __init__ > parameters = [utils.eval_param(param, self) for param in parameters] > File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 205, > in eval_param > TypeLookupError)) > File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 115, > in call_with_error_handling > return callable(*args, **kwargs) > File > "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line > 1171, in new > return type_handler_class(*args, **kwargs) > TypeError: __init__() takes at least 4 arguments (3 given) I know the exception message isn't terribly informative, but you are missing an argument. should be: retval('PyObject*', caller_owns_return=True|False) and: param('PyObject*', 'name', transfer_ownership=True|False) caller_owns_return indicates whether the caller owns the returned PyObject* reference or not. tranfer_ownership tells whether the callee expects to own the reference passed in. I am unable to say, in your example, what are the correct values. Only the implementation file can tell. Hope it helps. -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From aeriksson at gmail.com Thu Aug 21 09:06:57 2008 From: aeriksson at gmail.com (Andreas Eriksson) Date: Thu, 21 Aug 2008 09:06:57 +0200 Subject: [C++-sig] pybindgen and PyQt Message-ID: <1f4b35e00808210006r66135dcfr1d52678adc0eac1@mail.gmail.com> Hi, does anyone know if pybindgen plays nicely with PyQt (which uses SIP for wrapping)? Can C++ class wrapped with pybindgen be passed to PyQt? Regards, Andreas From ivanov.maxim at gmail.com Thu Aug 21 09:35:59 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Thu, 21 Aug 2008 11:35:59 +0400 Subject: [C++-sig] copy_const_reference on add_property In-Reply-To: <7465b6170808201122x72a9710ev59d7232278beafdb@mail.gmail.com> References: <7465b6170808201122x72a9710ev59d7232278beafdb@mail.gmail.com> Message-ID: > You should use boost::python::make_function > > namespace bp = boost::python; > > .add_property( > "name" > > , bp::make_function( > , ) ); > Works great. Thank you. From ivanov.maxim at gmail.com Thu Aug 21 11:30:23 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Thu, 21 Aug 2008 13:30:23 +0400 Subject: [C++-sig] non const std::string* as argument Message-ID: Hi all! How to export to python class members like "bool SerializeToString(string* output) const"? In python strings are immutables, so there is no way to export this method directly. So I tried to write a wrapper: std::string& wrap_SerializeToString(const gp::Message& msg) { std::string tmp; msg.SerializeToString(&tmp); return tmp; }; and then how I use it. Message class is base class for Link which I try to export to python, but Link never overrides SerializeToString. bp::class_("Message", bp::no_init) .def("SerializeToString", wrap_SerializeToString, bp::return_value_policy References: Message-ID: <7465b6170808210238m6675c83btfeb2520dc7560078@mail.gmail.com> On Thu, Aug 21, 2008 at 12:30 PM, Max Ivanov wrote: > Hi all! > How to export to python class members like "bool > SerializeToString(string* output) const"? In python strings are > immutables, so there is no way to export this method directly. So I > tried to write a wrapper: > > std::string& wrap_SerializeToString(const gp::Message& msg) { > std::string tmp; > msg.SerializeToString(&tmp); > return tmp; > }; Just remove reference from return type and you should be fine. > and then how I use it. Like any other class method. > Message class is base class for Link which I > try to export to python, but Link never overrides SerializeToString. What? > bp::class_("Message", bp::no_init) > .def("SerializeToString", wrap_SerializeToString, > bp::return_value_policy > gcc errors are following: > bindings.cpp: In function 'std::string& wrap_SerializeToString(const > google::protobuf::Message&)': > bindings.cpp:21: warning: reference to local variable 'tmp' returned > bindings.cpp: In function 'void init_module__spidermsg()': > bindings.cpp:46: error: a call to a constructor cannot appear in a > constant-expression > bindings.cpp:46: error: template argument 1 is invalid Take a look on Py++ "Function Transformation" feature: http://language-binding.net/pyplusplus/documentation/functions/transformation/transformation.html It deals with such "wrappers". -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From ivanov.maxim at gmail.com Thu Aug 21 12:31:31 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Thu, 21 Aug 2008 14:31:31 +0400 Subject: [C++-sig] non const std::string* as argument In-Reply-To: <7465b6170808210238m6675c83btfeb2520dc7560078@mail.gmail.com> References: <7465b6170808210238m6675c83btfeb2520dc7560078@mail.gmail.com> Message-ID: >> std::string& wrap_SerializeToString(const gp::Message& msg) { >> std::string tmp; >> msg.SerializeToString(&tmp); >> return tmp; >> }; > > Just remove reference from return type and you should be fine. I've remove reference and bp::return_value_policy... from .def and everything goes fine now, thanks again. >> Message class is base class for Link which I >> try to export to python, but Link never overrides SerializeToString. > > What? I've Link class which I tried to export to Python Initially, which is subclass of Message. > Take a look on Py++ "Function Transformation" feature: > http://language-binding.net/pyplusplus/documentation/functions/transformation/transformation.html > > It deals with such "wrappers". Lot's of nice docs there, nice. From ivanov.maxim at gmail.com Thu Aug 21 12:31:31 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Thu, 21 Aug 2008 14:31:31 +0400 Subject: [C++-sig] non const std::string* as argument In-Reply-To: <7465b6170808210238m6675c83btfeb2520dc7560078@mail.gmail.com> References: <7465b6170808210238m6675c83btfeb2520dc7560078@mail.gmail.com> Message-ID: >> std::string& wrap_SerializeToString(const gp::Message& msg) { >> std::string tmp; >> msg.SerializeToString(&tmp); >> return tmp; >> }; > > Just remove reference from return type and you should be fine. I've remove reference and bp::return_value_policy... from .def and everything goes fine now, thanks again. >> Message class is base class for Link which I >> try to export to python, but Link never overrides SerializeToString. > > What? I've Link class which I tried to export to Python Initially, which is subclass of Message. > Take a look on Py++ "Function Transformation" feature: > http://language-binding.net/pyplusplus/documentation/functions/transformation/transformation.html > > It deals with such "wrappers". Lot's of nice docs there, nice. From gjcarneiro at gmail.com Thu Aug 21 13:47:27 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Thu, 21 Aug 2008 12:47:27 +0100 Subject: [C++-sig] pybindgen and PyQt In-Reply-To: <1f4b35e00808210006r66135dcfr1d52678adc0eac1@mail.gmail.com> References: <1f4b35e00808210006r66135dcfr1d52678adc0eac1@mail.gmail.com> Message-ID: 2008/8/21 Andreas Eriksson > Hi, > > does anyone know if pybindgen plays nicely with PyQt (which uses SIP > for wrapping)? Can C++ class wrapped with pybindgen be passed to PyQt? For one thing, I find it hard to believe that PyQt would have any API that accepts an arbitrary class. At most I would believe in PyQt accepting an arbitrary subclass of a well known C++ base class wrapped by PyQt. So I am guessing you mean pybindgen wrapping a subclass of a PyQt-wrapped class. That I'm afraid will not work. Pybindgen does not allow subclassing classes defined in foreign wrapping tools. They would need to agree on many subtle details (instance structure layout and C++ object memory management protocol) to make it work, and it's very complicated. So, not going to happen. Sorry. -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.bilokon at lehman.com Thu Aug 21 14:00:58 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Thu, 21 Aug 2008 13:00:58 +0100 Subject: [C++-sig] Container Conversions: Wrapping Functions Expecting Non-const References Message-ID: Hi C++-sig, I am looking at scitbx/boost_python/container_conversions.h, which I think was written by Ralf Grosse-Kunstleve: http://cci.lbl.gov/~rwgk/shortcuts/htdocs/current/c_plus_plus/container_ _conversions_8h-source.html It's a great tool for something like displayVector below, which accepts its parameter by value: template void displayVector(vector<_Element> v) { typedef vector<_Element> Vector; typedef Vector::iterator VectorIterator; VectorIterator vend = v.end(); for (VectorIterator iter = v.begin(); iter != vend; ++iter) { cout << " - " << *iter << endl; } } I can wrap something like this into Python: class_("ContainersExample2", init<>()) .def("displayVectorOfInts", &ContainersExample2::displayVector) .def("displayVectorOfStrings", &ContainersExample2::displayVector) ... No problem, as long as I also have this: container_conversions::from_python_sequence, container_conversions::variable_capacity_policy>(); container_conversions::from_python_sequence, container_conversions::variable_capacity_policy>(); But what about the following method: template void doubleVector(vector<_Element> & v) { typedef vector<_Element> Vector; typedef Vector::iterator VectorIterator; VectorIterator vend = v.end(); for (VectorIterator iter = v.begin(); iter != vend; ++iter) { *iter *= 2; } } Here I have difficulties: Boost.Python.ArgumentError: Python argument types in ContainersExample2.doubleVectorOfInts(ContainersExample2, list) did not match C++ signature: doubleVectorOfInts(class ContainersExample2 {lvalue}, class std::vector > {lvalue}) What's the recommended technique(s) for this situation? Many thanks, Paul - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From aeriksson at gmail.com Thu Aug 21 14:32:00 2008 From: aeriksson at gmail.com (Andreas Eriksson) Date: Thu, 21 Aug 2008 14:32:00 +0200 Subject: [C++-sig] pybindgen and PyQt In-Reply-To: References: <1f4b35e00808210006r66135dcfr1d52678adc0eac1@mail.gmail.com> Message-ID: <1f4b35e00808210532g252d2df0mf4885bc972feda66@mail.gmail.com> Thanks for the reply Gustavo. >> does anyone know if pybindgen plays nicely with PyQt (which uses SIP >> for wrapping)? Can C++ class wrapped with pybindgen be passed to PyQt? > > For one thing, I find it hard to believe that PyQt would have any API that > accepts an arbitrary class. At most I would believe in PyQt accepting an > arbitrary subclass of a well known C++ base class wrapped by PyQt. So I am > guessing you mean pybindgen wrapping a subclass of a PyQt-wrapped class. > That I'm afraid will not work. Actually, it is the first scenario that I am after. Let me describe in some detail what I am after (slightly simplified): We have a C++ class that derives from the C++ Qt class QWidget. Lets call it OwnWidget. Several Qt methods expects pointers to subclasses of QWidget, such as QLayout::addWidget(QWidget*). Using the PyQt bindings I can create a python QLayout object. Now, what I want to do is create a pybindgen wrapped OwnWidget instance and pass it to the addWidget method of the PyQt QLayout object. The following pseudo-code illustrates what I want to do. I tried it using boost.python but without any luck. C++: #include class OwnWidget : public QWidget { ... } python: import pyqt import ownwidget # wrapped using pybindgen myWidget = ownwidget.OwnWidget() layout = pyqt.QLayout() layout.addWidget(myWidget) Regards, Andreas From gjcarneiro at gmail.com Thu Aug 21 15:47:40 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Thu, 21 Aug 2008 14:47:40 +0100 Subject: [C++-sig] pybindgen and PyQt In-Reply-To: <1f4b35e00808210532g252d2df0mf4885bc972feda66@mail.gmail.com> References: <1f4b35e00808210006r66135dcfr1d52678adc0eac1@mail.gmail.com> <1f4b35e00808210532g252d2df0mf4885bc972feda66@mail.gmail.com> Message-ID: 2008/8/21 Andreas Eriksson > Thanks for the reply Gustavo. > > >> does anyone know if pybindgen plays nicely with PyQt (which uses SIP > >> for wrapping)? Can C++ class wrapped with pybindgen be passed to PyQt? > > > > For one thing, I find it hard to believe that PyQt would have any API > that > > accepts an arbitrary class. At most I would believe in PyQt accepting an > > arbitrary subclass of a well known C++ base class wrapped by PyQt. So I > am > > guessing you mean pybindgen wrapping a subclass of a PyQt-wrapped class. > > That I'm afraid will not work. > > Actually, it is the first scenario that I am after. Let me describe in > some detail what I am after (slightly simplified): > > We have a C++ class that derives from the C++ Qt class QWidget. Lets > call it OwnWidget. Several Qt methods expects pointers to subclasses > of QWidget, such as QLayout::addWidget(QWidget*). Using the PyQt > bindings I can create a python QLayout object. Now, what I want to do > is create a pybindgen wrapped OwnWidget instance and pass it to the > addWidget method of the PyQt QLayout object. > > The following pseudo-code illustrates what I want to do. I tried it > using boost.python but without any luck. I'm sure that boost::python would have had the exact same problem. There is no 'standard' for the layout and policy of python object instances wrapping underlying C++ objects, therefore different wrapping tools cannot subclass each other's classes. Moreover, if you wrap in pybindgen both QWidget and OwnWidget, it may work on its own "world", but then if you pass a OwnWidget instance into PyQt it will not recognize it as being a pyqt.Widget type. It's a parallel type hierarchy from the point of view of python. I'm afraid I really don't have any simple solution for you. The easiest way this could work would be via double wrappers. The same OwnWidget would have to have an initial wrapper created by pybindgen, then an utility function that you add to the module would create a pyqt wrapper for the pybindgen wrapped object, which you can then use in pyqt. The utility conversion function needs to be written manually, with knowledge of the SIP API, and added with Module.add_custom_function_wrapper(). And this only works if you do not subclass OwnWidget in Python, because pybindgen then assumes it has the only wrapper for an object; with two wrappers reference counting fails and you get memory leaks. It is probably easier just to wrap everything in SIP... :P > > C++: > > #include > class OwnWidget : public QWidget { ... } > > python: > > import pyqt > import ownwidget # wrapped using pybindgen > > myWidget = ownwidget.OwnWidget() > layout = pyqt.QLayout() > layout.addWidget(myWidget) > > Regards, > > Andreas > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From william.marie at gmail.com Thu Aug 21 19:22:31 2008 From: william.marie at gmail.com (=?UTF-8?Q?William_Mari=C3=A9?=) Date: Thu, 21 Aug 2008 10:22:31 -0700 (PDT) Subject: [C++-sig] Calling overidden pure virtual function from C++ side Message-ID: <19093207.post@talk.nabble.com> Hi, I have a little problem using a pure virtual function exposed to the python and called from the c++ : In C++ : -------------------------- class A { virtual void foo() = 0; void bar() { foo(); } } struct AWrap : A, bp::wrapper { void foo() { this->get_override( "foo" ); } }; BOOST_PYTHON_MODULE(dum) { bp::class_( "A" ) .def( "foo", bp::pure_virtual( &A::foo ) ) .def( "bar", &A::bar ) ; } In Python : -------------------------- import dum class B( dum.A ) : def foo : print "Foo from B" b = B() b.bar() So here b.bar() never prints "Foo from B" Does anyone could tell me what am i doing wrong ? Thanks William -- View this message in context: http://www.nabble.com/Calling-overidden-pure-virtual-function-from-C%2B%2B-side-tp19093207p19093207.html Sent from the Python - c++-sig mailing list archive at Nabble.com. From roman.yakovenko at gmail.com Thu Aug 21 19:27:43 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 21 Aug 2008 20:27:43 +0300 Subject: [C++-sig] Calling overidden pure virtual function from C++ side In-Reply-To: <19093207.post@talk.nabble.com> References: <19093207.post@talk.nabble.com> Message-ID: <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> On Thu, Aug 21, 2008 at 8:22 PM, William Mari? wrote: > > Hi, > > I have a little problem using a pure virtual function exposed to the python > and called from the c++ : > > In C++ : > -------------------------- > class A > { > virtual void foo() = 0; > void bar() > { > foo(); > } > } > > struct AWrap : A, bp::wrapper > { > void foo() > { > this->get_override( "foo" ); > } > }; > > BOOST_PYTHON_MODULE(dum) > { > bp::class_( "A" ) > .def( "foo", bp::pure_virtual( &A::foo ) ) > .def( "bar", &A::bar ) > ; > } > > In Python : > -------------------------- > import dum > class B( dum.A ) : Try to add __init__ method def __init__( self ): dum.A.__init__( self ) -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From ope-devel at gmx.de Thu Aug 21 19:31:04 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Thu, 21 Aug 2008 19:31:04 +0200 Subject: [C++-sig] [pybindgen] Problems on class constructor Message-ID: <48ADA658.6080709@gmx.de> Hi, given the following header: ---8<--- class PyConsole; class StdoutPy { public: StdoutPy(PyConsole* console); void write(PyObject* args); void flush(); private: PyConsole* m_console; }; class PyConsole { void writeOut(PyObject* args); void writeErr(PyObject* args); void flush(); }; --->8--- and the python script: ---8<--- import pybindgen import sys # convenience param=pybindgen.param retval=pybindgen.retval pybindgen.settings.min_python_version = (2,5) mod = pybindgen.Module('redirector') mod.add_include('"redirector.hpp"') stdout_py = mod.add_class('StdoutPy') stdout_py.add_constructor([param('PyConsole*', 'cpp_parent', transfer_ownership=False)]) stdout_py.add_method('write', None, [param('PyObject*', 'value', transfer_ownership=False)]) stdout_py.add_method('flush', None, []) mod.generate(sys.stdout) --->8--- I get the error: $ python redirector.py Traceback (most recent call last): File "redirector.py", line 14, in stdout_py.add_constructor([param('PyConsole*', 'cpp_parent', transfer_ownership=False)]) File "/usr/lib/python2.5/site-packages/pybindgen/cppclass.py", line 1228, in add_constructor constructor = CppConstructor(*args, **kwargs) File "/usr/lib/python2.5/site-packages/pybindgen/cppmethod.py", line 415, in __init__ parameters = [utils.eval_param(param, self) for param in parameters] File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 205, in eval_param TypeLookupError)) File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 115, in call_with_error_handling return callable(*args, **kwargs) File "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line 1167, in new param_type_matcher.lookup(ctype) File "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line 1300, in lookup raise TypeLookupError(name) pybindgen.typehandlers.base.TypeLookupError: PyConsole * It seems, that I have to register my own types but I have no idea how to do this. For Testing I've used the xmlgcc approach: ---8<--- import sys from pybindgen import FileCodeSink from pybindgen.gccxmlparser import ModuleParser def my_module_gen(): module_parser = ModuleParser('redirector', '::') module_parser.parse([sys.argv[1]], include_paths=['/usr/include/python2.5'],includes=['"redirector.hpp"'], pygen_sink=FileCodeSink(sys.stdout)) if __name__ == '__main__': my_module_gen() --->8--- which results in errors too: /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:580: DeprecationWarning: Parameter include_paths is deprecated, use gccxml_options instead self.parse_init(header_files, include_paths, whitelist_paths, includes, pygen_sink, pygen_classifier) INFO Parsing source file "redirector.hpp" ... INFO gccxml cmd: /usr/bin/gccxml -I"." -I"/usr/include/python2.5" "redirector.hpp" -fxml="/tmp/tmp5ORqw3.xml" INFO GCCXML version - 0.7 /usr/lib/python2.5/site-packages/pygccxml/parser/scanner.py:335: UserWarning: unable to find out array size from expression "" warnings.warn( msg ) from pybindgen import Module, FileCodeSink, param, retval, cppclass import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('redirector', cpp_namespace='::') root_module.add_include('"redirector.hpp"') return root_module def register_types(module): root_module = module.get_root() module.add_class('StdoutPy') module.add_class('PyConsole') ## Register a nested module for the namespace std nested_module = module.add_cpp_namespace('std') register_types_std(nested_module) def register_types_std(module): root_module = module.get_root() def register_methods(root_module): register_StdoutPy_methods(root_module, root_module['StdoutPy']) register_PyConsole_methods(root_module, root_module['PyConsole']) return def register_StdoutPy_methods(root_module, cls): /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:215: UserWarning: multiple &'s not handled warnings.warn("multiple &'s not handled") /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:211: UserWarning: multiple consts not handled warnings.warn("multiple consts not handled") cls.add_constructor([param('StdoutPy&', '_ctor_arg', is_const=True)]) cls.add_constructor([param('PyConsole *', 'console')]) /var/tmp/redirector.hpp:12: WrapperWarning: Parameter '::PyConsole * console' error (used in StdoutPy::StdoutPy(PyConsole * console) [constructor]): TypeConfigurationError('transfer_ownership parameter missing',) StdoutPy(PyConsole* console); cls.add_method('write', 'void', [param('PyObject *', 'args')]) /usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py:1173: UserWarning: Exception '__init__() takes at least 4 arguments (3 given)' in type handler constructor warnings.warn("Exception %r in type handler %s constructor" % (str(ex), type_handler_class)) Traceback (most recent call last): File "redirector_py.py", line 13, in my_module_gen() File "redirector_py.py", line 10, in my_module_gen module_parser.parse([sys.argv[1]], include_paths=['/usr/include/python2.5'],includes=['"redirector.hpp"'], pygen_sink=FileCodeSink(sys.stdout)) File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", line 582, in parse self.scan_methods() File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", line 809, in scan_methods self._scan_class_methods(class_wrapper.gccxml_definition, class_wrapper, pygen_sink) File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", line 1420, in _scan_class_methods arguments.append(Parameter.new(*arg[0], **arg[1])) File "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line 1171, in new return type_handler_class(*args, **kwargs) TypeError: __init__() takes at least 4 arguments (3 given) BTW, how can I prevent the construction of the StdoutPy class from python? It has to be created from c++ side. Thanks, Olaf From william.marie at gmail.com Thu Aug 21 19:50:59 2008 From: william.marie at gmail.com (=?ISO-8859-1?Q?william_mari=E9?=) Date: Thu, 21 Aug 2008 18:50:59 +0100 Subject: [C++-sig] Calling overidden pure virtual function from C++ side In-Reply-To: <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> References: <19093207.post@talk.nabble.com> <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> Message-ID: <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> Hi, It's already done sorry, i didn't write the __init__ function in the post : def __init__( self ) : dum.A.__init__( self ) Even with that it's not working, can we normally call virtual function from the C++ side ? 2008/8/21 Roman Yakovenko > On Thu, Aug 21, 2008 at 8:22 PM, William Mari? > wrote: > > > > Hi, > > > > I have a little problem using a pure virtual function exposed to the > python > > and called from the c++ : > > > > In C++ : > > -------------------------- > > class A > > { > > virtual void foo() = 0; > > void bar() > > { > > foo(); > > } > > } > > > > struct AWrap : A, bp::wrapper > > { > > void foo() > > { > > this->get_override( "foo" ); > > } > > }; > > > > BOOST_PYTHON_MODULE(dum) > > { > > bp::class_( "A" ) > > .def( "foo", bp::pure_virtual( &A::foo ) ) > > .def( "bar", &A::bar ) > > ; > > } > > > > In Python : > > -------------------------- > > import dum > > class B( dum.A ) : > > Try to add __init__ method > > def __init__( self ): > dum.A.__init__( self ) > > > -- > Roman Yakovenko > C++ Python language binding > http://www.language-binding.net/ > _______________________________________________ > 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 gjcarneiro at gmail.com Thu Aug 21 20:00:07 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Thu, 21 Aug 2008 19:00:07 +0100 Subject: [C++-sig] [pybindgen] Problems on class constructor In-Reply-To: <48ADA658.6080709@gmx.de> References: <48ADA658.6080709@gmx.de> Message-ID: 2008/8/21 Olaf Peter > Hi, > > given the following header: > > ---8<--- > class PyConsole; > > class StdoutPy > { > public: > StdoutPy(PyConsole* console); > void write(PyObject* args); > void flush(); > private: > PyConsole* m_console; > }; > > class PyConsole > { > void writeOut(PyObject* args); > void writeErr(PyObject* args); > void flush(); > }; > --->8--- > > > and the python script: > > ---8<--- > import pybindgen > import sys > > # convenience > param=pybindgen.param > retval=pybindgen.retval > > pybindgen.settings.min_python_version = (2,5) > > mod = pybindgen.Module('redirector') > mod.add_include('"redirector.hpp"') > > stdout_py = mod.add_class('StdoutPy') > stdout_py.add_constructor([param('PyConsole*', 'cpp_parent', > transfer_ownership=False)]) > stdout_py.add_method('write', None, [param('PyObject*', 'value', > transfer_ownership=False)]) > stdout_py.add_method('flush', None, []) > > mod.generate(sys.stdout) > --->8--- > > I get the error: > > $ python redirector.py > Traceback (most recent call last): > File "redirector.py", line 14, in > stdout_py.add_constructor([param('PyConsole*', 'cpp_parent', > transfer_ownership=False)]) > File "/usr/lib/python2.5/site-packages/pybindgen/cppclass.py", line > 1228, in add_constructor > constructor = CppConstructor(*args, **kwargs) > File "/usr/lib/python2.5/site-packages/pybindgen/cppmethod.py", line > 415, in __init__ > parameters = [utils.eval_param(param, self) for param in parameters] > File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 205, > in eval_param > TypeLookupError)) > File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 115, > in call_with_error_handling > return callable(*args, **kwargs) > File > "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line > 1167, in new > param_type_matcher.lookup(ctype) > File > "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line > 1300, in lookup > raise TypeLookupError(name) > pybindgen.typehandlers.base.TypeLookupError: PyConsole * > > > It seems, that I have to register my own types but I have no idea how to > do this. You just have to declare the PyConsole class, with: mod.add_class('PyConsole') For Testing I've used the xmlgcc approach: > > ---8<--- > import sys > > from pybindgen import FileCodeSink > from pybindgen.gccxmlparser import ModuleParser > > def my_module_gen(): > module_parser = ModuleParser('redirector', '::') > module_parser.parse([sys.argv[1]], > include_paths=['/usr/include/python2.5'],includes=['"redirector.hpp"'], > pygen_sink=FileCodeSink(sys.stdout)) > > if __name__ == '__main__': > my_module_gen() > --->8--- > > which results in errors too: > > /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:580: > DeprecationWarning: Parameter include_paths is deprecated, use > gccxml_options instead > self.parse_init(header_files, include_paths, whitelist_paths, > includes, pygen_sink, pygen_classifier) > > INFO Parsing source file "redirector.hpp" ... > > INFO gccxml cmd: /usr/bin/gccxml -I"." -I"/usr/include/python2.5" > "redirector.hpp" -fxml="/tmp/tmp5ORqw3.xml" > > INFO GCCXML version - 0.7 > /usr/lib/python2.5/site-packages/pygccxml/parser/scanner.py:335: > UserWarning: unable to find out array size from expression "" > warnings.warn( msg ) > from pybindgen import Module, FileCodeSink, param, retval, cppclass > > > import pybindgen.settings > import warnings > > class ErrorHandler(pybindgen.settings.ErrorHandler): > def handle_error(self, wrapper, exception, traceback_): > warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) > return True > pybindgen.settings.error_handler = ErrorHandler() > > > import sys > > def module_init(): > root_module = Module('redirector', cpp_namespace='::') > root_module.add_include('"redirector.hpp"') > return root_module > > def register_types(module): > root_module = module.get_root() > > module.add_class('StdoutPy') > module.add_class('PyConsole') > > ## Register a nested module for the namespace std > > nested_module = module.add_cpp_namespace('std') > register_types_std(nested_module) > > > def register_types_std(module): > root_module = module.get_root() > > > def register_methods(root_module): > register_StdoutPy_methods(root_module, root_module['StdoutPy']) > register_PyConsole_methods(root_module, root_module['PyConsole']) > return > > def register_StdoutPy_methods(root_module, cls): > /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:215: > UserWarning: multiple &'s not handled > warnings.warn("multiple &'s not handled") > /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:211: > UserWarning: multiple consts not handled > warnings.warn("multiple consts not handled") > cls.add_constructor([param('StdoutPy&', '_ctor_arg', is_const=True)]) > cls.add_constructor([param('PyConsole *', 'console')]) > /var/tmp/redirector.hpp:12: WrapperWarning: Parameter '::PyConsole * > console' error (used in StdoutPy::StdoutPy(PyConsole * console) > [constructor]): TypeConfigurationError('transfer_ownership parameter > missing',) > StdoutPy(PyConsole* console); > cls.add_method('write', > 'void', > [param('PyObject *', 'args')]) > /usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py:1173: > UserWarning: Exception '__init__() takes at least 4 arguments (3 given)' > in type handler 'pybindgen.typehandlers.pyobjecttype.PyObjectParam'> constructor > warnings.warn("Exception %r in type handler %s constructor" % > (str(ex), type_handler_class)) > Traceback (most recent call last): > File "redirector_py.py", line 13, in > my_module_gen() > File "redirector_py.py", line 10, in my_module_gen > module_parser.parse([sys.argv[1]], > include_paths=['/usr/include/python2.5'],includes=['"redirector.hpp"'], > pygen_sink=FileCodeSink(sys.stdout)) > File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", > line 582, in parse > self.scan_methods() > File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", > line 809, in scan_methods > self._scan_class_methods(class_wrapper.gccxml_definition, > class_wrapper, pygen_sink) > File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", > line 1420, in _scan_class_methods > arguments.append(Parameter.new(*arg[0], **arg[1])) > File > "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line > 1171, in new > return type_handler_class(*args, **kwargs) > TypeError: __init__() takes at least 4 arguments (3 given) I am guessing you need to add a transfer_ownership=false annotation in some places. I know, annotations are not properly documented, so I don't blame you for the mistake :P I think your header file would need something like this (check the -#- comments): class PyConsole; class StdoutPy { public: // -#- @console(transfer_ownership=false) -#- StdoutPy(PyConsole* console); // -#- @args(transfer_ownership=false) -#- void write(PyObject* args); void flush(); private: PyConsole* m_console; }; class PyConsole { // -#- @args(transfer_ownership=false) -#- void writeOut(PyObject* args); // -#- @args(transfer_ownership=false) -#- void writeErr(PyObject* args); void flush(); }; > > BTW, how can I prevent the construction of the StdoutPy class from > python? It has to be created from c++ side. Using gccxml scanner, there's no easy way to do it. I guess that, after scanning, you can reset the list of constructors to the empty list: module['StdoutPy'].constructors = [] Using the python API interface you just don't declare to pybindgen that a class has a public constructor, and pybindgen will generate a special constructor that raises an exception saying the class cannot be constructed. -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Thu Aug 21 20:01:27 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 21 Aug 2008 21:01:27 +0300 Subject: [C++-sig] Calling overidden pure virtual function from C++ side In-Reply-To: <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> References: <19093207.post@talk.nabble.com> <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> Message-ID: <7465b6170808211101v3217a569g1d8f5b6a1348fa10@mail.gmail.com> 2008/8/21 william mari? : > Hi, > > It's already done sorry, i didn't write the __init__ function in the post : > def __init__( self ) : > dum.A.__init__( self ) > > Even with that it's not working, can we normally call virtual function from > the C++ side ? Here is an exercise for you: find the difference between your code and the one, that were generated by Py++: #include "boost/python.hpp" #include "1.h" namespace bp = boost::python; struct A_wrapper : A, bp::wrapper< A > { A_wrapper() : A() , bp::wrapper< A >(){ // null constructor } virtual void foo( ){ bp::override func_foo = this->get_override( "foo" ); func_foo( ); } }; BOOST_PYTHON_MODULE(pyplusplus){ bp::class_< A_wrapper, boost::noncopyable >( "A" ) .def( "bar" , (void ( ::A::* )( ) )( &::A::bar ) ) .def( "foo" , bp::pure_virtual( (void ( ::A::* )( ) )(&::A::foo) ) ); } P.S. Next time try to post example, which contains "the whole picture". -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From seefeld at sympatico.ca Thu Aug 21 20:01:58 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 21 Aug 2008 14:01:58 -0400 Subject: [C++-sig] Calling overidden pure virtual function from C++ side In-Reply-To: <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> References: <19093207.post@talk.nabble.com> <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> Message-ID: <48ADAD96.5000102@sympatico.ca> william mari? wrote: > > > > struct AWrap : A, bp::wrapper > > { > > void foo() > > { > > this->get_override( "foo" ); > > } > > }; > You retrieve the override, but you don't call it. See http://www.boost.org/doc/libs/1_36_0/libs/python/doc/v2/wrapper.html#examples HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From gjcarneiro at gmail.com Thu Aug 21 20:05:10 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Thu, 21 Aug 2008 19:05:10 +0100 Subject: [C++-sig] [pybindgen] Problems on class constructor In-Reply-To: References: <48ADA658.6080709@gmx.de> Message-ID: 2008/8/21 Gustavo Carneiro > > > 2008/8/21 Olaf Peter > > Hi, >> >> given the following header: >> >> ---8<--- >> class PyConsole; >> >> class StdoutPy >> { >> public: >> StdoutPy(PyConsole* console); >> void write(PyObject* args); >> void flush(); >> private: >> PyConsole* m_console; >> }; >> >> class PyConsole >> { >> void writeOut(PyObject* args); >> void writeErr(PyObject* args); >> void flush(); >> }; >> --->8--- >> >> >> and the python script: >> >> ---8<--- >> import pybindgen >> import sys >> >> # convenience >> param=pybindgen.param >> retval=pybindgen.retval >> >> pybindgen.settings.min_python_version = (2,5) >> >> mod = pybindgen.Module('redirector') >> mod.add_include('"redirector.hpp"') >> >> stdout_py = mod.add_class('StdoutPy') >> stdout_py.add_constructor([param('PyConsole*', 'cpp_parent', >> transfer_ownership=False)]) >> stdout_py.add_method('write', None, [param('PyObject*', 'value', >> transfer_ownership=False)]) >> stdout_py.add_method('flush', None, []) >> >> mod.generate(sys.stdout) >> --->8--- >> >> I get the error: >> >> $ python redirector.py >> Traceback (most recent call last): >> File "redirector.py", line 14, in >> stdout_py.add_constructor([param('PyConsole*', 'cpp_parent', >> transfer_ownership=False)]) >> File "/usr/lib/python2.5/site-packages/pybindgen/cppclass.py", line >> 1228, in add_constructor >> constructor = CppConstructor(*args, **kwargs) >> File "/usr/lib/python2.5/site-packages/pybindgen/cppmethod.py", line >> 415, in __init__ >> parameters = [utils.eval_param(param, self) for param in parameters] >> File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 205, >> in eval_param >> TypeLookupError)) >> File "/usr/lib/python2.5/site-packages/pybindgen/utils.py", line 115, >> in call_with_error_handling >> return callable(*args, **kwargs) >> File >> "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line >> 1167, in new >> param_type_matcher.lookup(ctype) >> File >> "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line >> 1300, in lookup >> raise TypeLookupError(name) >> pybindgen.typehandlers.base.TypeLookupError: PyConsole * >> >> >> It seems, that I have to register my own types but I have no idea how to >> do this. > > > You just have to declare the PyConsole class, with: > mod.add_class('PyConsole') > > For Testing I've used the xmlgcc approach: >> >> ---8<--- >> import sys >> >> from pybindgen import FileCodeSink >> from pybindgen.gccxmlparser import ModuleParser >> >> def my_module_gen(): >> module_parser = ModuleParser('redirector', '::') >> module_parser.parse([sys.argv[1]], >> include_paths=['/usr/include/python2.5'],includes=['"redirector.hpp"'], >> pygen_sink=FileCodeSink(sys.stdout)) >> >> if __name__ == '__main__': >> my_module_gen() >> --->8--- >> >> which results in errors too: >> >> /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:580: >> DeprecationWarning: Parameter include_paths is deprecated, use >> gccxml_options instead >> self.parse_init(header_files, include_paths, whitelist_paths, >> includes, pygen_sink, pygen_classifier) >> >> INFO Parsing source file "redirector.hpp" ... >> >> INFO gccxml cmd: /usr/bin/gccxml -I"." -I"/usr/include/python2.5" >> "redirector.hpp" -fxml="/tmp/tmp5ORqw3.xml" >> >> INFO GCCXML version - 0.7 >> /usr/lib/python2.5/site-packages/pygccxml/parser/scanner.py:335: >> UserWarning: unable to find out array size from expression "" >> warnings.warn( msg ) >> from pybindgen import Module, FileCodeSink, param, retval, cppclass >> >> >> import pybindgen.settings >> import warnings >> >> class ErrorHandler(pybindgen.settings.ErrorHandler): >> def handle_error(self, wrapper, exception, traceback_): >> warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) >> return True >> pybindgen.settings.error_handler = ErrorHandler() >> >> >> import sys >> >> def module_init(): >> root_module = Module('redirector', cpp_namespace='::') >> root_module.add_include('"redirector.hpp"') >> return root_module >> >> def register_types(module): >> root_module = module.get_root() >> >> module.add_class('StdoutPy') >> module.add_class('PyConsole') >> >> ## Register a nested module for the namespace std >> >> nested_module = module.add_cpp_namespace('std') >> register_types_std(nested_module) >> >> >> def register_types_std(module): >> root_module = module.get_root() >> >> >> def register_methods(root_module): >> register_StdoutPy_methods(root_module, root_module['StdoutPy']) >> register_PyConsole_methods(root_module, root_module['PyConsole']) >> return >> >> def register_StdoutPy_methods(root_module, cls): >> /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:215: >> UserWarning: multiple &'s not handled >> warnings.warn("multiple &'s not handled") >> /usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py:211: >> UserWarning: multiple consts not handled >> warnings.warn("multiple consts not handled") >> cls.add_constructor([param('StdoutPy&', '_ctor_arg', is_const=True)]) >> cls.add_constructor([param('PyConsole *', 'console')]) >> /var/tmp/redirector.hpp:12: WrapperWarning: Parameter '::PyConsole * >> console' error (used in StdoutPy::StdoutPy(PyConsole * console) >> [constructor]): TypeConfigurationError('transfer_ownership parameter >> missing',) >> StdoutPy(PyConsole* console); >> cls.add_method('write', >> 'void', >> [param('PyObject *', 'args')]) >> /usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py:1173: >> UserWarning: Exception '__init__() takes at least 4 arguments (3 given)' >> in type handler > 'pybindgen.typehandlers.pyobjecttype.PyObjectParam'> constructor >> warnings.warn("Exception %r in type handler %s constructor" % >> (str(ex), type_handler_class)) >> Traceback (most recent call last): >> File "redirector_py.py", line 13, in >> my_module_gen() >> File "redirector_py.py", line 10, in my_module_gen >> module_parser.parse([sys.argv[1]], >> include_paths=['/usr/include/python2.5'],includes=['"redirector.hpp"'], >> pygen_sink=FileCodeSink(sys.stdout)) >> File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", >> line 582, in parse >> self.scan_methods() >> File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", >> line 809, in scan_methods >> self._scan_class_methods(class_wrapper.gccxml_definition, >> class_wrapper, pygen_sink) >> File "/usr/lib/python2.5/site-packages/pybindgen/gccxmlparser.py", >> line 1420, in _scan_class_methods >> arguments.append(Parameter.new(*arg[0], **arg[1])) >> File >> "/usr/lib/python2.5/site-packages/pybindgen/typehandlers/base.py", line >> 1171, in new >> return type_handler_class(*args, **kwargs) >> TypeError: __init__() takes at least 4 arguments (3 given) > > > I am guessing you need to add a transfer_ownership=false annotation in some > places. I know, annotations are not properly documented, so I don't blame > you for the mistake :P > > I think your header file would need something like this (check the -#- > comments): > > class PyConsole; > > class StdoutPy > { > public: > // -#- @console(transfer_ownership=false) -#- > StdoutPy(PyConsole* console); > // -#- @args(transfer_ownership=false) -#- > void write(PyObject* args); > void flush(); > private: > PyConsole* m_console; > }; > > class PyConsole > { > // -#- @args(transfer_ownership=false) -#- > void writeOut(PyObject* args); > // -#- @args(transfer_ownership=false) -#- > void writeErr(PyObject* args); > void flush(); > }; > > >> >> BTW, how can I prevent the construction of the StdoutPy class from >> python? It has to be created from c++ side. >> > > Using gccxml scanner, there's no easy way to do it. I guess that, after > scanning, you can reset the list of constructors to the empty list: > module['StdoutPy'].constructors = [] > After hitting send I remembered... A less hackish way to do it with the gccxml scanner is to add 'ignore' annotations to the constructors. class PyConsole { public: // -#- ignore -#- PyConsole () {} // need to make the constructor explicit for this to work... [...] }; P. S.: the annotations system is rather fragile. Annotations are looked for in the line above the line where GCC-XML reports that the declaration is defined. But GCC-XML reports weird line numbers on multi-line declarations, so beware. -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From william.marie at gmail.com Thu Aug 21 20:15:22 2008 From: william.marie at gmail.com (=?ISO-8859-1?Q?william_mari=E9?=) Date: Thu, 21 Aug 2008 19:15:22 +0100 Subject: [C++-sig] Calling overidden pure virtual function from C++ side In-Reply-To: <48ADAD96.5000102@sympatico.ca> References: <19093207.post@talk.nabble.com> <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> <48ADAD96.5000102@sympatico.ca> Message-ID: <168485c00808211115o1cb4d9cevd87b643ab1867791@mail.gmail.com> Thanks Stefan, sorry... silly mistake... William 2008/8/21 Stefan Seefeld > william mari? wrote: > >> >> >> > struct AWrap : A, bp::wrapper >> > { >> > void foo() >> > { >> > this->get_override( "foo" ); >> > } >> > }; >> >> > You retrieve the override, but you don't call it. See > > http://www.boost.org/doc/libs/1_36_0/libs/python/doc/v2/wrapper.html#examples > > 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 troy at resophonic.com Thu Aug 21 20:10:43 2008 From: troy at resophonic.com (troy d. straszheim) Date: Thu, 21 Aug 2008 14:10:43 -0400 Subject: [C++-sig] Calling overidden pure virtual function from C++ side In-Reply-To: <48ADAD96.5000102@sympatico.ca> References: <19093207.post@talk.nabble.com> <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> <48ADAD96.5000102@sympatico.ca> Message-ID: <48ADAFA3.2070504@resophonic.com> Stefan Seefeld wrote: > william mari? wrote: >> > struct AWrap : A, bp::wrapper and you're low on CRTP struct AWrap : A, bp::wrapper { -t From seefeld at sympatico.ca Thu Aug 21 20:35:40 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 21 Aug 2008 14:35:40 -0400 Subject: [C++-sig] Calling overidden pure virtual function from C++ side In-Reply-To: <48ADAFA3.2070504@resophonic.com> References: <19093207.post@talk.nabble.com> <7465b6170808211027p4b978d9dua57fee622d792e27@mail.gmail.com> <168485c00808211050l6f04f83cqf6bb3ae133308a4a@mail.gmail.com> <48ADAD96.5000102@sympatico.ca> <48ADAFA3.2070504@resophonic.com> Message-ID: <48ADB57C.1000502@sympatico.ca> troy d. straszheim wrote: > Stefan Seefeld wrote: >> william mari? wrote: > >>> > struct AWrap : A, bp::wrapper > > and you're low on CRTP > > struct AWrap : A, bp::wrapper { I suspect that might be an issue with his mailer client, eating angular brackets. Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From ivanov.maxim at gmail.com Thu Aug 21 21:51:09 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Thu, 21 Aug 2008 23:51:09 +0400 Subject: [C++-sig] returning pointer to instance and object ownership Message-ID: Hi all! Some newbie questions again. class B {} class A { B* add(); } method "add" of class A creates a new instance of class B and stores reference to it somewhere inside. I'm trying to expose it to python this way: ".def("add", &A::add, bp::return_value_policy())" It works ok. If I change returned B instance I'm able to see changes accessing them from A instance - I hope that means that returned pointer and one stored inside A are related to same instance. Problems accour when I try to delete objects: a = A() b = a.add() del b del a Segmentation fault. It's the simpliest case I could imagine, since add() method should always return new object, but still couldn't understand how to do it right. ps. I've no control over A and B sources. From dave at boostpro.com Fri Aug 22 02:51:14 2008 From: dave at boostpro.com (David Abrahams) Date: Thu, 21 Aug 2008 16:51:14 -0800 Subject: [C++-sig] Alternate packaging technique for bindings + pure python In-Reply-To: <48A9B063.8070503@resophonic.com> (troy d. straszheim's message of "Mon, 18 Aug 2008 13:24:51 -0400") References: <48A9B063.8070503@resophonic.com> Message-ID: <87vdxt3m9p.fsf@mcbain.luannocracy.com> on Mon Aug 18 2008, "troy d. straszheim" wrote: > def load_pybindings(name, path): > """ > Merges python bindings from shared library 'name' into module 'name'. > Use when you have a directory structure:: > > lib/ > foo.so > foo/ > __init__.py > something.py > > Here, inside ``foo/__init__.py`` call ``load_pybindings(__name__, __path__)`` > > this assumes that the first entry in list ``__path__`` is where > you want the wrapped classes to merge to. > > """ > import imp, sys > m = imp.load_dynamic(name, __path__[0] + ".so") > thismod = sys.modules[name] > > for (k,v) in m.__dict__.items(): > if not k.startswith("_"): > thismod.__dict__[k] = v > > Wherein you just use the __name__ and __path__ of the current module being imported to > locate and load the associated shared library. Then you copy the symbols into the > current library. > > So the call to it in each __init__.py would be: > > load_pybindings(__name__, __path__) > > Nice thing is that everything looks quite homogenous to the user. It appears to work > quite well, but I just now came up with this and thought I ask if anybody > sees any problems. As Hans said, I'd want to check that it interacts well with everything else before recommending it, but also I'd want to check that it works properly on Windows as well as *nix. If it does continue to work well, I would be very happy if you would volunteer to rewrite that part of the tutorial :-) -- Dave Abrahams BoostPro Computing http://www.boostpro.com From dave at boostpro.com Fri Aug 22 02:56:47 2008 From: dave at boostpro.com (David Abrahams) Date: Thu, 21 Aug 2008 16:56:47 -0800 Subject: [C++-sig] Accessing python configuration data when building extensions using bjam and boost.python In-Reply-To: <60825b0f0808182207k62f65c5aq1771aafb9d412836@mail.gmail.com> (Greg Landrum's message of "Tue, 19 Aug 2008 07:07:22 +0200") References: <60825b0f0808182207k62f65c5aq1771aafb9d412836@mail.gmail.com> Message-ID: <87k5e93m0g.fsf@mcbain.luannocracy.com> on Mon Aug 18 2008, "Greg Landrum" wrote: > So I need to add something like this to my > Jamroot : > gcc:/usr/lib/python2.5/site-packages/numpy/core/include > This is, obviously, dependent on operating system, python version and > python installation-location. So the user will have to edit the > Jamroot based on their details. One of the things I really like about > boost.build is that this kind of stuff is normally not required. I think that sort of thing is what site-config.jam is designed for. > I could solve this problem, I think, there were a variable (?) in > python.jam defining the location of python's "lib" directory that I > could access from my Jamroot. Then I could have something like: > $(python-lib-dir)/numpy/core/include > that would work on every machine. > > I've spent some time looking through the boost.build documentation and > python.jam, but I was unable to figure out how to expose a new > variable that would be accessible from other Jamfiles. > > Does anyone have a recipe for doing this? If you find you need to do something like this, I strongly suggest asking about it on the boost-build list. -- Dave Abrahams BoostPro Computing http://www.boostpro.com From dave at boostpro.com Fri Aug 22 05:28:37 2008 From: dave at boostpro.com (David Abrahams) Date: Thu, 21 Aug 2008 19:28:37 -0800 Subject: [C++-sig] Static and non-static functions with the same name In-Reply-To: (Paul Bilokon's message of "Wed, 20 Aug 2008 09:40:04 +0100") References: <200808191052.36559.lists_ravi@lavabit.com> Message-ID: <877ia920ey.fsf@mcbain.luannocracy.com> on Wed Aug 20 2008, "Bilokon, Paul" wrote: > Hi Ravi, > > If my understanding is correct, this method has the same deficiency as > simply doing this: > > // OK, explicitly specifying the static garply(string): > .def("staticGarply", (string (*)(string)) &Foo::garply) > .staticmethod("staticGarply") > // OK, explicitly specifying the non-static garply(int, int): > .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > > // NB: The syntax: (*) for static, (Foo::*) for non-static > > // NB: Since staticmethod does not distinguish between the method > // signatures, we must give the static and non-static variants > // distinct names in Python > > This works, but the static and non-static variants end up having different > names on the Python side. There's not much you can really do about that, since there's no real overloading in Python; it's just simulated by Boost.Python. -- Dave Abrahams BoostPro Computing http://www.boostpro.com From roman.yakovenko at gmail.com Fri Aug 22 11:27:10 2008 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Fri, 22 Aug 2008 12:27:10 +0300 Subject: [C++-sig] returning pointer to instance and object ownership In-Reply-To: References: Message-ID: <7465b6170808220227x152919f6r72c5ea3b79e4918c@mail.gmail.com> On Thu, Aug 21, 2008 at 10:51 PM, Max Ivanov wrote: > Hi all! Some newbie questions again. > > class B {} > > class A { > B* add(); > } > > method "add" of class A creates a new instance of class B and stores > reference to it somewhere inside. Class A is responcible for the deletion, right? > I'm trying to expose it to python this way: > ".def("add", &A::add, bp::return_value_policy())" If the answer to my question is "yes", that you should use "return_internal_reference" call policy. http://www.boost.org/doc/libs/1_36_0/libs/python/doc/v2/return_internal_reference.html#return_internal_reference-spec -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From paul.bilokon at lehman.com Fri Aug 22 14:21:04 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Fri, 22 Aug 2008 13:21:04 +0100 Subject: [C++-sig] Static and non-static functions with the same name In-Reply-To: <877ia920ey.fsf@mcbain.luannocracy.com> References: <200808191052.36559.lists_ravi@lavabit.com> <877ia920ey.fsf@mcbain.luannocracy.com> Message-ID: Thanks Dave, Having different names for the static / non-static methods on the Python side is not too big a problem. Many thanks, Paul -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of David Abrahams Sent: Friday, August 22, 2008 4:29 AM To: Development of Python/C++ integration Subject: Re: [C++-sig] Static and non-static functions with the same name on Wed Aug 20 2008, "Bilokon, Paul" wrote: > Hi Ravi, > > If my understanding is correct, this method has the same deficiency as > simply doing this: > > // OK, explicitly specifying the static garply(string): > .def("staticGarply", (string (*)(string)) &Foo::garply) > .staticmethod("staticGarply") > // OK, explicitly specifying the non-static garply(int, int): > .def("garply", (string (Foo::*)(int, int)) &Foo::garply) > > // NB: The syntax: (*) for static, (Foo::*) for non-static > > // NB: Since staticmethod does not distinguish between the method > // signatures, we must give the static and non-static variants > // distinct names in Python > > This works, but the static and non-static variants end up having > different names on the Python side. There's not much you can really do about that, since there's no real overloading in Python; it's just simulated by Boost.Python. -- Dave Abrahams BoostPro Computing http://www.boostpro.com _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From ivanov.maxim at gmail.com Fri Aug 22 23:16:13 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Sat, 23 Aug 2008 01:16:13 +0400 Subject: [C++-sig] returning pointer to instance and object ownership In-Reply-To: <7465b6170808220227x152919f6r72c5ea3b79e4918c@mail.gmail.com> References: <7465b6170808220227x152919f6r72c5ea3b79e4918c@mail.gmail.com> Message-ID: > If the answer to my question is "yes", that you should use > "return_internal_reference" call policy. > http://www.boost.org/doc/libs/1_36_0/libs/python/doc/v2/return_internal_reference.html#return_internal_reference-spec I see now, that Boost::python is all about wrappers :) From ope-devel at gmx.de Sat Aug 23 19:01:49 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Sat, 23 Aug 2008 19:01:49 +0200 Subject: [C++-sig] [pybindgen] parameter defaults Message-ID: <48B0427D.8070706@gmx.de> Hello, how can I emulate/code a py function that excepts a default type, e.g. stdin.read(size=None) in C/pybindgen which can called as stdin.read() and stdin.read(100). This has to configure in the pybindgen's python script, but I did not found this. stdin_py.add_method('read', retval('PyObject*', caller_owns_return=False), [param('int', 'size=None')]) doesn't generate code as expected. BTW, retval should be a python string ( Py_BuildValue((char *) "s", retval); ). How to get this? Thanks, Olaf From ope-devel at gmx.de Sat Aug 23 19:34:17 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Sat, 23 Aug 2008 19:34:17 +0200 Subject: [C++-sig] [pybindgen] parameter defaults In-Reply-To: <48B0427D.8070706@gmx.de> References: <48B0427D.8070706@gmx.de> Message-ID: <48B04A19.1030006@gmx.de> > stdin_py.add_method('read', retval('PyObject*', > caller_owns_return=False), [param('int', 'size=None')]) therefore the C code must like shown something like: PyObject * PyRedirectIn_read(PyRedirectIn *self, PyObject *args, PyObject *kwargs) { int size = std::numeric_limits::max(); const char *keywords[] = {"size", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "|i", (char **) keywords, &size)) { return NULL; } QString retval = self->obj->read_fn(size); PyObject *py_retval = Py_BuildValue((char *) "s", static_cast(retval.toUtf8())); return py_retval; } From gjcarneiro at gmail.com Sat Aug 23 23:10:39 2008 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Sat, 23 Aug 2008 22:10:39 +0100 Subject: [C++-sig] [pybindgen] parameter defaults In-Reply-To: <48B04A19.1030006@gmx.de> References: <48B0427D.8070706@gmx.de> <48B04A19.1030006@gmx.de> Message-ID: 2008/8/23 Olaf Peter > > > stdin_py.add_method('read', retval('PyObject*', > > caller_owns_return=False), [param('int', 'size=None')]) > > therefore the C code must like shown something like: > > > PyObject * > PyRedirectIn_read(PyRedirectIn *self, PyObject *args, PyObject *kwargs) > { > int size = std::numeric_limits::max(); > const char *keywords[] = {"size", NULL}; > > if (!PyArg_ParseTupleAndKeywords(args, kwargs, (char *) "|i", (char > **) keywords, &size)) { > return NULL; > } > > QString retval = self->obj->read_fn(size); > PyObject *py_retval = Py_BuildValue((char *) "s", static_cast char*>(retval.toUtf8())); > > return py_retval; > } > To support the default value, use: param('int', 'size', default_value='std::numeric_limits::max()'). To handle QString return value you'd have to write your own return type handler for QString. But it doesn't sound complicated. You just have to declare a class similar to StdStringReturn in pybindgen/typehandlers/stringtype.py. Untested code: class QStringReturnValue(ReturnValue): CTYPES = ['QString'] def get_c_error_return(self): return "return QString();" def convert_python_to_c(self, wrapper): raise NotImplementedError # TODO (needed only for virtual methods where C calls Python code) def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("s", ['%s.toUtf8()' % self.value ], prepend=True) After the class is declared, you can use retval('QString') as return value. Hope this helps. -- Gustavo J. A. M. Carneiro INESC Porto, Telecommunications and Multimedia Unit "The universe is always one step beyond logic." -- Frank Herbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From gupta.sandeep at gmail.com Sun Aug 24 20:58:06 2008 From: gupta.sandeep at gmail.com (Sandeep Gupta) Date: Sun, 24 Aug 2008 11:58:06 -0700 Subject: [C++-sig] [BGL] python bindings for intel compiler Message-ID: <98a412be0808241158t1794ac38y6ac854cc401b06cb@mail.gmail.com> Hi, I haven't been able to create correct python bindings for BGL for intel compiler. Will greatly appreciate any help as it has been more than four months since I first encountered the problem. The python bindings in the tutorial and examples work fine. The bgl_python code from the sandbox compiles smoothly. I believe I have set the PYTHONPATH and LD_LIBRARY_PATH correctly. But the import of boost.graph fails with following error: Traceback (most recent call last): File "", line 1, in File "...../bgl-python/lib/python/boost/graph/__init__.py", line 16, in from boost.graph._graph import * ImportError: "...../bgl-python/lib/python/boost/graph/_graph.so: undefined symbol: _ZN5boost5graph6python11basic_graphINS_11undirectedSEED1Ev" Thanks, Sandeep -------------- next part -------------- An HTML attachment was scrubbed... URL: From srmandrake at yahoo.com Mon Aug 25 04:09:06 2008 From: srmandrake at yahoo.com (SrMandrake ElMago) Date: Sun, 24 Aug 2008 19:09:06 -0700 (PDT) Subject: [C++-sig] Py_Finalize() crashes when PyImport_Import() fails Message-ID: <637465.86127.qm@web56204.mail.re3.yahoo.com> Hello, I am triying to learn some Python to use it with C++. After some time I managed to do what I was attempting, but I just realized a couple of days ago that there is a problem when I call Py_Finalize() just before my program exits. The problem is as follows: First of all, I am using VC Express 2005, on Windows XP. My program is able to do everything perfectly as long as the script to load is found. When the script is not found, the program keeps going perfectly, but crashes when calling Py_Finalize() raising an exception and poping the following message. Exception exceptions.ImportError: 'No module named test_11' in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection Now, I know the easiest solution to the problem is to put the file where it is supposed to be :-), but what I'm actually looking for is a way to prevent the error from?crashing the program?because, at the end, I would like the user to type?the name of the file (script)?to load (and there?may be a typo or the entered file name may not?exist )?Thanks in advance for any help you can give me... Rod- Here's the code... #include ? int main() { Py_Initialize (); //"test_1" is the actual name of the file. I changed it to "test_11" on purpose to cause the crash... const char* s = "test_11"; PyObject* pName = PyString_FromString ( s ); PyObject* pModule = PyImport_Import ( pName ); if ( !pModule ) {??? ??? std::cout << "Unable to open script " << s << std::endl; ??? getchar (); } Py_XDECREF( pModule ); Py_XDECREF( pName ); Py_Finalize (); getchar (); return0; } -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Mon Aug 25 04:31:42 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Sun, 24 Aug 2008 22:31:42 -0400 Subject: [C++-sig] Py_Finalize() crashes when PyImport_Import() fails In-Reply-To: <637465.86127.qm@web56204.mail.re3.yahoo.com> References: <637465.86127.qm@web56204.mail.re3.yahoo.com> Message-ID: <48B2198E.1030306@sympatico.ca> SrMandrake ElMago wrote: > > Exception exceptions.ImportError: 'No module named test_11' in > 'garbage collection' ignored > Fatal Python error: unexpected exception during garbage collection The Python runtime may expect you to call handle Python exceptions explicitely, prior to finalizing. > if ( !pModule ) > > { > If you got 0 here, Python has set an exception. Before moving on you should handle it, for example by explicitely clearing it: PyErr_Clear(); > std::cout << "Unable to open script " << s << std::endl; > > getchar (); > > } > > > > Py_XDECREF( pModule ); > > Py_XDECREF( pName ); > > > > Py_Finalize (); > With the above addition, the Python runtime should finalize fine. HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From srmandrake at yahoo.com Mon Aug 25 05:29:04 2008 From: srmandrake at yahoo.com (SrMandrake ElMago) Date: Sun, 24 Aug 2008 20:29:04 -0700 (PDT) Subject: [C++-sig] Py_Finalize() crashes when PyImport_Import() fails Message-ID: <373824.3843.qm@web56213.mail.re3.yahoo.com> That was it! Thanks Stefan... If ever in Costa Rica...email me. I'll buy u a beer! :-D Pura Vida (Y) ----- Original Message ---- From: Stefan Seefeld To: Development of Python/C++ integration Sent: Sunday, August 24, 2008 8:31:42 PM Subject: Re: [C++-sig] Py_Finalize() crashes when PyImport_Import() fails SrMandrake ElMago wrote: > > Exception exceptions.ImportError: 'No module named test_11' in > 'garbage collection' ignored > Fatal Python error: unexpected exception during garbage collection The Python runtime may expect you to call handle Python exceptions explicitely, prior to finalizing. > if ( !pModule ) > > { > If you got 0 here, Python has set an exception. Before moving on you should handle it, for example by explicitely clearing it: PyErr_Clear(); >? ? std::cout << "Unable to open script " << s << std::endl; > >? ? getchar (); > > } > >? > > Py_XDECREF( pModule ); > > Py_XDECREF( pName ); > >? > > Py_Finalize (); > With the above addition, the Python runtime should finalize fine. 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 rwgk at yahoo.com Mon Aug 25 11:48:54 2008 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 25 Aug 2008 02:48:54 -0700 (PDT) Subject: [C++-sig] Container Conversions: Wrapping Functions Expecting Non-const References Message-ID: <487287.80500.qm@web31403.mail.mud.yahoo.com> Hi Paul, > Here I have difficulties: > > Boost.Python.ArgumentError: Python argument types in > ContainersExample2.doubleVectorOfInts(ContainersExample2, list) > did not match C++ signature: > doubleVectorOfInts(class ContainersExample2 {lvalue}, class > std::vector > {lvalue}) > > What's the recommended technique(s) for this situation? Boost.Python doesn't have "on-the-fly converters with write-back" (long story). You have to wrap std::vector "properly" if you want to pass non-const references to C++. The vector-indexing suite is an option that should work well. Or you can follow this more minimalistic example: http://cctbx.svn.sourceforge.net/viewvc/cctbx/trunk/scitbx/stl/vector_wrapper.h?view=markup Ignore the ref_from_array code near the bottom. Ralf From paul.bilokon at lehman.com Wed Aug 27 13:01:36 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Wed, 27 Aug 2008 12:01:36 +0100 Subject: [C++-sig] Container Conversions: Wrapping Functions ExpectingNon-const References In-Reply-To: <487287.80500.qm@web31403.mail.mud.yahoo.com> References: <487287.80500.qm@web31403.mail.mud.yahoo.com> Message-ID: Hi Ralf, Many thanks for your explanation. I see there are two options: on-the-fly converters without write-back and wrappers (a la the vector indexing suite, or perhaps the set wrapper). In essence, the former can be used for passing values, the latter for passing references. I have also tried adding conversions for a few simple types (e.g. std::pairs and boost::tuples) to see how they work. Looks like they do the trick. Many thanks, Paul -----Original Message----- From: c++-sig-bounces+paul.bilokon=lehman.com at python.org [mailto:c++-sig-bounces+paul.bilokon=lehman.com at python.org] On Behalf Of Ralf W. Grosse-Kunstleve Sent: Monday, August 25, 2008 10:49 AM To: Development of Python/C++ integration Subject: Re: [C++-sig] Container Conversions: Wrapping Functions ExpectingNon-const References Hi Paul, > Here I have difficulties: > > Boost.Python.ArgumentError: Python argument types in > ContainersExample2.doubleVectorOfInts(ContainersExample2, list) > did not match C++ signature: > doubleVectorOfInts(class ContainersExample2 {lvalue}, class > std::vector > {lvalue}) > > What's the recommended technique(s) for this situation? Boost.Python doesn't have "on-the-fly converters with write-back" (long story). You have to wrap std::vector "properly" if you want to pass non-const references to C++. The vector-indexing suite is an option that should work well. Or you can follow this more minimalistic example: http://cctbx.svn.sourceforge.net/viewvc/cctbx/trunk/scitbx/stl/vector_wr apper.h?view=markup Ignore the ref_from_array code near the bottom. Ralf _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. -------------- next part -------------- A non-text attachment was scrubbed... Name: StdPairConversions.h Type: application/octet-stream Size: 3270 bytes Desc: StdPairConversions.h URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: BoostTupleConversions.h Type: application/octet-stream Size: 22972 bytes Desc: BoostTupleConversions.h URL: From ope-devel at gmx.de Wed Aug 27 21:22:20 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Wed, 27 Aug 2008 21:22:20 +0200 Subject: [C++-sig] [boost.python] PyErr_Fetch and object Message-ID: <48B5A96C.3040403@gmx.de> Hi, following http://www.python.org/doc/api/exceptionHandling.html, PyErr_Fetch returns objects and I own these (if!= NULL). I wrote: bpl::object exception, value, tb; PyErr_Fetch(&exception.ptr(), &value.ptr(), &tb.ptr()); which doesn't compile: error: lvalue required as unary '&' operand is there a way for this using bpl:object? Maybe I have to wrap this after calling PyErr_Fetch? Thanks, Olaf From seefeld at sympatico.ca Wed Aug 27 21:45:08 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 27 Aug 2008 15:45:08 -0400 Subject: [C++-sig] [boost.python] PyErr_Fetch and object In-Reply-To: <48B5A96C.3040403@gmx.de> References: <48B5A96C.3040403@gmx.de> Message-ID: <48B5AEC4.7020409@sympatico.ca> Olaf Peter wrote: > Hi, > > following http://www.python.org/doc/api/exceptionHandling.html, > PyErr_Fetch returns objects and I own these (if!= NULL). > > I wrote: > > bpl::object exception, value, tb; > PyErr_Fetch(&exception.ptr(), &value.ptr(), &tb.ptr()); > I wouldn't expect this to work: You can't assign to the return value of bpl::object::ptr(). > is there a way for this using bpl:object? Not at this time. > Maybe I have to wrap this > after calling PyErr_Fetch? > Yes. Something like this should work: namespace boost { namespace python { void fetch_error(object &type, object &value, object &traceback) { PyObject *t, *v, *b; PyErr_Fetch(&t, &v, &b); type = detail::new_reference(t); value = v ? detail::new_reference(v) : object(); traceback = b ? detail::new_reference(b) : object(); } } } (There are more functions like this that could be added. Some day I'll submit a new patch... HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From ope-devel at gmx.de Thu Aug 28 07:25:23 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Thu, 28 Aug 2008 07:25:23 +0200 Subject: [C++-sig] [boost.python] PyErr_Fetch and object In-Reply-To: <48B5AEC4.7020409@sympatico.ca> References: <48B5A96C.3040403@gmx.de> <48B5AEC4.7020409@sympatico.ca> Message-ID: <48B636C3.5030505@gmx.de> >> Maybe I have to wrap this >> after calling PyErr_Fetch? >> > Yes. Something like this should work: > > namespace boost > { > namespace python > { > void fetch_error(object &type, object &value, object &traceback) > { > PyObject *t, *v, *b; > PyErr_Fetch(&t, &v, &b); > type = detail::new_reference(t); > value = v ? detail::new_reference(v) : object(); > traceback = b ? detail::new_reference(b) : object(); > } > } > } > > (There are more functions like this that could be added. Some day I'll > submit a new patch... Thanks, would be great. Anyway, In the source of boost.python I saw a lot of used detail::.. stuff. The raw:pyobject header says this are to hide to the user. What are the correspondent user functions for new_reference, borrowed_reference and new_non_null_reference which are more in common sense of the python C/API documentation. Thanks, Olaf From amohr at pixar.com Thu Aug 28 19:03:12 2008 From: amohr at pixar.com (Alex Mohr) Date: Thu, 28 Aug 2008 10:03:12 -0700 Subject: [C++-sig] [boost.python] PyErr_Fetch and object In-Reply-To: <48B636C3.5030505@gmx.de> References: <48B5A96C.3040403@gmx.de> <48B5AEC4.7020409@sympatico.ca> <48B636C3.5030505@gmx.de> Message-ID: <48B6DA50.20005@pixar.com> >> Yes. Something like this should work: >> >> void fetch_error(object &type, object &value, object &traceback) >> { >> PyObject *t, *v, *b; >> PyErr_Fetch(&t, &v, &b); >> type = detail::new_reference(t); >> value = v ? detail::new_reference(v) : object(); >> traceback = b ? detail::new_reference(b) : object(); >> } >> >> (There are more functions like this that could be added. Some day I'll >> submit a new patch... > > Thanks, would be great. Anyway, In the source of boost.python I saw a > lot of used detail::.. stuff. The raw:pyobject header says this are to > hide to the user. What are the correspondent user functions for > new_reference, borrowed_reference and new_non_null_reference which are > more in common sense of the python C/API documentation. I tried to rewrite the above using more public-api. Also I think the original function does not check 't' for NULL, and so may only be safely called if there is a python exception. I tried to change it so this code will set all three objects to None if there is no exception. I haven't tried compiling or testing this. void fetch_error(object &type, object &value, object &traceback) { PyObject *t, *v, *b; PyErr_Fetch(&t, &v, &b); type = object(handle<>(allow_null(t))); value = object(handle<>(allow_null(v))); traceback = object(handle<>(allow_null(b)); } Alex From seefeld at sympatico.ca Thu Aug 28 19:14:15 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 28 Aug 2008 13:14:15 -0400 Subject: [C++-sig] [boost.python] PyErr_Fetch and object In-Reply-To: <48B6DA50.20005@pixar.com> References: <48B5A96C.3040403@gmx.de> <48B5AEC4.7020409@sympatico.ca> <48B636C3.5030505@gmx.de> <48B6DA50.20005@pixar.com> Message-ID: <48B6DCE7.5000807@sympatico.ca> Alex Mohr wrote: >> >> Thanks, would be great. Anyway, In the source of boost.python I saw a >> lot of used detail::.. stuff. The raw:pyobject header says this are >> to hide to the user. What are the correspondent user functions for >> new_reference, borrowed_reference and new_non_null_reference which >> are more in common sense of the python C/API documentation. > > I tried to rewrite the above using more public-api. Also I think the > original function does not check 't' for NULL, and so may only be > safely called if there is a python exception. I tried to change it so > this code will set all three objects to None if there is no exception. > > I haven't tried compiling or testing this. > > void fetch_error(object &type, object &value, object &traceback) { > PyObject *t, *v, *b; > PyErr_Fetch(&t, &v, &b); > type = object(handle<>(allow_null(t))); > value = object(handle<>(allow_null(v))); > traceback = object(handle<>(allow_null(b)); > } Thanks ! Actually, the lack of a check for 'type' was intentional: Even if an error is set, 'value' and 'traceback' may be set to NULL. 'type' can only be NULL if no error is set, and thus has to be handled special. (For example, we could throw an exception in that case, as calling fetch_error if no error is set is an error (or may be, if we make it so). Of course, with that then come other function wrappers for 'restore', 'clear', etc. I'll think about a patch, if no-one else beats me to it Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From amohr at pixar.com Thu Aug 28 19:47:00 2008 From: amohr at pixar.com (Alex Mohr) Date: Thu, 28 Aug 2008 10:47:00 -0700 Subject: [C++-sig] [boost.python] PyErr_Fetch and object In-Reply-To: <48B6DCE7.5000807@sympatico.ca> References: <48B5A96C.3040403@gmx.de> <48B5AEC4.7020409@sympatico.ca> <48B636C3.5030505@gmx.de> <48B6DA50.20005@pixar.com> <48B6DCE7.5000807@sympatico.ca> Message-ID: <48B6E494.6060908@pixar.com> > Thanks ! Actually, the lack of a check for 'type' was intentional: Even > if an error is set, 'value' and 'traceback' may be set to NULL. > 'type' can only be NULL if no error is set, and thus has to be handled > special. (For example, we could throw an exception in that case, as > calling fetch_error if no error is set is an error (or may be, if we > make it so). Hmm -- well, my personal preference is for it to mimic the python c api, so if there is no error set, then all three are set to None, if there is an error set, then type is not None, and value and traceback may or may not be None. That's how I tried to write it. > Of course, with that then come other function wrappers for 'restore', > 'clear', etc. Indeed. It would be nice to do a project that tried to wrap up all (or as much as possible) of the python C api. That would benefit and appeal to a wide audience, I think. Even including folks who don't use boost.python to generate bindings. > I'll think about a patch, if no-one else beats me to it :) Alex From azan00 at yahoo.com Thu Aug 28 23:32:53 2008 From: azan00 at yahoo.com (Brian Dawn) Date: Thu, 28 Aug 2008 14:32:53 -0700 (PDT) Subject: [C++-sig] [boost.python] Assertion Fails with return_value_policy Message-ID: <580094.27248.qm@web54409.mail.yahoo.com> Hi, I currently have a function that returns an object pointer. I wish to expose this function to python. However when I set a return_value_policy to this member function I get the following assertion failure. Assertion failed! Program: ... File: libs\python\src\converter\registry.cpp Line: 207 Expression: slot->m_to_python == 0 I have been searching for a fix for quite a while. I have also tried many different return_value_policies. Below is the line causing the assertion failure. namespace["pyEmitter"] = boost::python::class_("pyEmitter") .def("grab", &pyEmitter::getParticle, boost::python::return_value_policy()); And here is my function. pyParticle& pyEmitter::getParticle() { return *particleList[0]; } I am using MS Visual Express 2008 if it matters, I have seen many examples and my code appears to be correct. Any help would be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From seefeld at sympatico.ca Thu Aug 28 23:44:19 2008 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 28 Aug 2008 17:44:19 -0400 Subject: [C++-sig] [boost.python] Assertion Fails with return_value_policy In-Reply-To: <580094.27248.qm@web54409.mail.yahoo.com> References: <580094.27248.qm@web54409.mail.yahoo.com> Message-ID: <48B71C33.4060308@sympatico.ca> Brian Dawn wrote: > Hi, I currently have a function that returns an object pointer. I wish > to expose this function to python. However when I set a > return_value_policy to this member function I get the following > assertion failure. This is a bug in boost.python. (Even if you do something wrong, the library shouldn't abort, but raise an exception, in that case.) Please submit an issue for this. Thanks, Stefan -- ...ich hab' noch einen Koffer in Berlin... From ope-devel at gmx.de Fri Aug 29 07:38:34 2008 From: ope-devel at gmx.de (Olaf Peter) Date: Fri, 29 Aug 2008 07:38:34 +0200 Subject: [C++-sig] [boost.python] PyErr_Fetch and object In-Reply-To: <48B6E494.6060908@pixar.com> References: <48B5A96C.3040403@gmx.de> <48B5AEC4.7020409@sympatico.ca> <48B636C3.5030505@gmx.de> <48B6DA50.20005@pixar.com> <48B6DCE7.5000807@sympatico.ca> <48B6E494.6060908@pixar.com> Message-ID: <48B78B5A.3090105@gmx.de> Alex Mohr schrieb: >> Thanks ! Actually, the lack of a check for 'type' was intentional: >> Even if an error is set, 'value' and 'traceback' may be set to NULL. >> 'type' can only be NULL if no error is set, and thus has to be handled >> special. (For example, we could throw an exception in that case, as >> calling fetch_error if no error is set is an error (or may be, if we >> make it so). > > Hmm -- well, my personal preference is for it to mimic the python c api, > so if there is no error set, then all three are set to None, if there is > an error set, then type is not None, and value and traceback may or may > not be None. That's how I tried to write it. which is intuitive to C/API. To check the case mentioned by Stefan one has to test on PyErr_Occured() and than decide the individual error handling. >> Of course, with that then come other function wrappers for 'restore', >> 'clear', etc. > > Indeed. It would be nice to do a project that tried to wrap up all (or > as much as possible) of the python C api. That would benefit and appeal > to a wide audience, I think. Even including folks who don't use > boost.python to generate bindings. > >> I'll think about a patch, if no-one else beats me to it I will do it too ;-) At this time I wrote my own extension to boost.python like the above. Anyway, what are the appropriate user functions for detail { new_reference, borrowed_reference and new_non_null_reference }? Why does detail::borrow owns a reference and do not decide the user what to do? Thanks, Olaf From dave at boostpro.com Fri Aug 29 12:18:11 2008 From: dave at boostpro.com (David Abrahams) Date: Fri, 29 Aug 2008 06:18:11 -0400 Subject: [C++-sig] [boost.python] Assertion Fails with return_value_policy In-Reply-To: <580094.27248.qm@web54409.mail.yahoo.com> (Brian Dawn's message of "Thu, 28 Aug 2008 14:32:53 -0700 (PDT)") References: <580094.27248.qm@web54409.mail.yahoo.com> Message-ID: <877ia0ruos.fsf@mcbain.luannocracy.com> on Thu Aug 28 2008, Brian Dawn wrote: > Hi, I currently have a function that returns an object pointer. I wish to expose > this function to python. However when I set a return_value_policy to this member > function I get the following assertion failure. > > Assertion failed! > Program: ... > File: libs\python\src\converter\registry.cpp > Line: 207 > Expression: slot->m_to_python == 0 It's hard for me to see how that could be the case. That assertion means you've tried to register to-python conversions for the same type twice. But the code you show below doesn't look like it should be registering any type converters, so it seems like the assertion probably comes from elsewhere (possibly a bug in your code). If you continue past that assertion (or skip over it in the debugger) you should observe the Python interpreter giving you the name of the offending C++ type, but given what I wrote above, I don't expect that to illuminate much. More likely it would be very useful to reduce your code to a minimal, complete example that reproduces the problem. If you don't discover a problem in your own code along the way, it will give us what we need to fix Boost.Python. I do agree with Stefan that there is a bug in Boost.Python here. The problem is that I never decided whether the condition detected by the assertion should be considered a precondition violation, and documented it accordingly. The response to the condition is suboptimal as a result. -- Dave Abrahams BoostPro Computing http://www.boostpro.com From paul.bilokon at lehman.com Fri Aug 29 16:01:38 2008 From: paul.bilokon at lehman.com (Bilokon, Paul) Date: Fri, 29 Aug 2008 15:01:38 +0100 Subject: [C++-sig] Attempt to Return Dangling Reference Error -- What's the solution? Message-ID: Hi, I'm looking at this: http://www.boost.org/doc/libs/1_36_0/libs/python/doc/v2/faq.html#danglin g ('I'm getting the "attempt to return dangling reference" error. What am I doing wrong?') I understand the statement of the problem. However, suppose I need to hold on to the new Python object and the C++ object contained therein. How do I achieve that? Let me give you the specific context. void takesAnimalRawPtr(Animal * animalRawPtr) { cout << "This is " << animalRawPtr->whatIsIt() << endl; Animal * clone = animalRawPtr->clone(); cout << "Now this is " << clone->whatIsIt() << endl; delete clone; } This works very well for a C++ child of Animal, Cat, which overrides the virtual method clone. This does not work for a Python child of Animal: class Dog(smartptr_step.Animal): def __init__(self): super(Dog, self).__init__() def whatIsIt(self): return "dog" def clone(self): dogClone = Dog() return dogClone Here I'm getting the aforementioned dangling reference. Can you please help? Many thanks, Paul - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. From dave at boostpro.com Fri Aug 29 16:52:43 2008 From: dave at boostpro.com (David Abrahams) Date: Fri, 29 Aug 2008 10:52:43 -0400 Subject: [C++-sig] Attempt to Return Dangling Reference Error -- What's the solution? In-Reply-To: (Paul Bilokon's message of "Fri, 29 Aug 2008 15:01:38 +0100") References: Message-ID: <87hc93ho04.fsf@mcbain.luannocracy.com> on Fri Aug 29 2008, "Bilokon, Paul" wrote: > Hi, > > I'm looking at this: > > http://www.boost.org/doc/libs/1_36_0/libs/python/doc/v2/faq.html#danglin > g > > ('I'm getting the "attempt to return dangling reference" error. What am > I doing wrong?') > > I understand the statement of the problem. However, suppose I need to > hold on to the new Python object and the C++ object contained therein. > How do I achieve that? > > Let me give you the specific context. > > > void takesAnimalRawPtr(Animal * animalRawPtr) > { > cout << "This is " << animalRawPtr->whatIsIt() << endl; > Animal * clone = animalRawPtr->clone(); > cout << "Now this is " << clone->whatIsIt() << endl; > delete clone; > } I suggest you make your clone() functions return a boost::shared_ptr. That would make all your problems disappear. HTH, -- Dave Abrahams BoostPro Computing http://www.boostpro.com From amohr at pixar.com Fri Aug 29 18:39:23 2008 From: amohr at pixar.com (Alex Mohr) Date: Fri, 29 Aug 2008 09:39:23 -0700 Subject: [C++-sig] [boost.python] PyErr_Fetch and object In-Reply-To: <48B78B5A.3090105@gmx.de> References: <48B5A96C.3040403@gmx.de> <48B5AEC4.7020409@sympatico.ca> <48B636C3.5030505@gmx.de> <48B6DA50.20005@pixar.com> <48B6DCE7.5000807@sympatico.ca> <48B6E494.6060908@pixar.com> <48B78B5A.3090105@gmx.de> Message-ID: <48B8263B.6010605@pixar.com> > Anyway, what are the appropriate user functions for > detail { new_reference, borrowed_reference and new_non_null_reference }? > Why does detail::borrow owns a reference and do not decide the user what > to do? I'd say just use handle<> if you can. It's a lightweight wrapper around PyObject * that manages the refcount for you. When constructing a handle<>, it by default assumes that the PyObject * you're passing to it is not null, and a "new reference" (meaning you already own a reference to it). But you can tell it otherwise by using allow_null() and borrowed(), either alone or in combination. Using borrowed() tells boost.python that the PyObject * is a "borrowed reference" meaning that you do not own a reference to it. In that case, handle<> will bump the reference count. Check out the docs: http://www.boost.org/doc/libs/1_36_0/libs/python/doc/v2/handle.html Alex From azan00 at yahoo.com Fri Aug 29 18:59:40 2008 From: azan00 at yahoo.com (Brian Dawn) Date: Fri, 29 Aug 2008 09:59:40 -0700 (PDT) Subject: [C++-sig] [boost.python] Assertion Fails with return_value_policy Message-ID: <774156.21199.qm@web54403.mail.yahoo.com> Thanks everyone for their replies. David you are correct, after ignoring the assertion failure it gave me the information I needed to find the flaw within my code. It was a typo, I had copied and pasted a class exposure line but forgot to actually change the name of the class (such a stupid mistake, but eh better than a major flaw). The assertion failure can be recreated (on my system at least) with the following two lines of code. global["class1"] = class_("class1"); global["class2"] = class_("class2"); ----- Original Message ---- From: David Abrahams To: Development of Python/C++ integration Sent: Friday, August 29, 2008 5:18:11 AM Subject: Re: [C++-sig] [boost.python] Assertion Fails with return_value_policy on Thu Aug 28 2008, Brian Dawn wrote: > Hi, I currently have a function that returns an object pointer. I wish to expose > this function to python. However when I set a return_value_policy to this member > function I get the following assertion failure. > > Assertion failed! > Program: ... > File: libs\python\src\converter\registry.cpp > Line: 207 > Expression: slot->m_to_python == 0 It's hard for me to see how that could be the case. That assertion means you've tried to register to-python conversions for the same type twice. But the code you show below doesn't look like it should be registering any type converters, so it seems like the assertion probably comes from elsewhere (possibly a bug in your code). If you continue past that assertion (or skip over it in the debugger) you should observe the Python interpreter giving you the name of the offending C++ type, but given what I wrote above, I don't expect that to illuminate much. More likely it would be very useful to reduce your code to a minimal, complete example that reproduces the problem. If you don't discover a problem in your own code along the way, it will give us what we need to fix Boost.Python. I do agree with Stefan that there is a bug in Boost.Python here. The problem is that I never decided whether the condition detected by the assertion should be considered a precondition violation, and documented it accordingly. The response to the condition is suboptimal as a result. -- Dave Abrahams BoostPro Computing http://www.boostpro.com _______________________________________________ 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 william.marie at gmail.com Sat Aug 30 16:35:52 2008 From: william.marie at gmail.com (=?UTF-8?Q?William_Mari=C3=A9?=) Date: Sat, 30 Aug 2008 07:35:52 -0700 (PDT) Subject: [C++-sig] How to link Python statically to boost python ? Message-ID: <19233904.post@talk.nabble.com> Hi, I would like to link statically python25.lib to boost-python.lib and then link statically boost-python.lib to my script.lib. i can't find a way to do that. Could someone tell me if it's possible and if yes how to do it ? Thanks William -- View this message in context: http://www.nabble.com/How-to-link-Python-statically-to-boost-python---tp19233904p19233904.html Sent from the Python - c++-sig mailing list archive at Nabble.com. From jlc at kergis.com Sun Aug 31 15:35:37 2008 From: jlc at kergis.com (jeanluc.c) Date: Sun, 31 Aug 2008 06:35:37 -0700 (PDT) Subject: [C++-sig] how to link project with a specified libpython in static? (using boost.Python) Message-ID: <19242281.post@talk.nabble.com> Hi, We would need help to solve a link problem on our project. We are developing a project using boost, boost.Python, and bjam, but we would like to embedded our own python library in static form. I'm currently developing on darwin (macosx 10.5). Python sources have been integrated in our project (/.../project_path/libs/Python), and we building the static library thanks to the Makefile (resulting in: /.../project_path/libs/Python/libpython2.5.a). Our project is using bjam, and in the Jamroot we define: ... using python : # 2.5 : /.../project_path/libs/Python/python # cmd-or-prefix : [ getPythonIncludePaths ] # includes (return: /.../project_path/libs/Python/Include ...) : [ getPythonLibPath ] # libraries (return: /.../project_path/libs/Python) : [ getPythonConditions ] #conditions (return: debug on static) ; ... The project Jamfile is: ... exe testscript : [ glob *.cpp ] /otherlib//otherlib /boost/python//boost_python/static /python//python/static ; The problem appear during the link stage, the generated g++ command looks like: g++ -L"/.../project_path/libs/Python" -I"/.../project_path/libs/Python/Include" ... -o testscript "/.../project_path/libs/sys/libotherlib.a" "/.../project_path/libs/boost/libs/python/.../boost_python.a" main.o ... -lpython2.5 -g This failed due to unresolved symbols with python library: Undefined symbols: "__Py_NegativeRefcount", referenced from: boost::python::detail::decref_guard::~decref_guard()in main.o ... Manually, I've tried: a) replace "-lpython2.5" by /.../project_path/libs/Python/libpython2.5.a : this is working just fine - the exe is linked and everything work b) rename the system python library "/usr/lib/libpython2.5.dylib" (so g++ cannot find it at link stage) : this is also working fine. So, by using -lpython2.5, we encourage g++ to find libraries in its standard paths, which I would like to avoid since we would like to statically build our own libpython. Is there any nice method to tell bjam / boost.python to use our own python library (in static)? A good way would be that bjam use the full path to the static version (project_path/libs/Python/libpython2.5.a) of it when linking exe to it, is there a way to do so? Thanks in advance for your help! Best regards, jeanluc -- View this message in context: http://www.nabble.com/how-to-link-project-with-a-specified-libpython-in-static--%28using-boost.Python%29-tp19242281p19242281.html Sent from the Python - c++-sig mailing list archive at Nabble.com.