From niki at vintech.bg Mon Oct 1 11:36:51 2007 From: niki at vintech.bg (niki) Date: Mon, 01 Oct 2007 12:36:51 +0300 Subject: [C++-sig] Announcing pybindgen In-Reply-To: <7465b6170709261308h571c91c3ofe5837dea5cc3a1d@mail.gmail.com> References: <7465b6170709261308h571c91c3ofe5837dea5cc3a1d@mail.gmail.com> Message-ID: <4700BFB3.2080608@vintech.bg> Roman Yakovenko wrote: > Although I like Py++ a lot, I really hate Boost.Python. Maybe it's > because of my lack of skill in understanding C++ templates, but I > feel like Boost.Python hides too many details underneath a layer of > cryptic to follow set of C++ templates, while I need to see the > generated code in order to check that memory management details are > being declared and implemented correctly. > > > :-), I think you are going to reinvent the wheel here. I guess there are > many reasons why memory management is complex and you eventually > rediscover all of them About reinventing the wheel: Pyrex/Cython has to deal with similar memory management problems. Maybe there are some parts to share? HTH Niki Spahiev From ropoctl at gmail.com Tue Oct 2 18:26:33 2007 From: ropoctl at gmail.com (Robert O'Callahan) Date: Tue, 2 Oct 2007 11:26:33 -0500 Subject: [C++-sig] Py++ question Message-ID: <3be982d00710020926v2b2885c4j68c4d2b25e3a9ab1@mail.gmail.com> I am trying to use a generate_code.py created by the py++ gui, but I get this error: Traceback (most recent call last): File "generate_code.py", line 40, in ? export() File "generate_code.py", line 37, in export mb.write_module( os.path.join( settings.generated_files_dir, settings.module_name + '.cpp') ) File "/usr/lib/python2.4/site-packages/pyplusplus/module_builder/builder.py", line 311, in write_module file_writers.write_file( self.code_creator, file_name, encoding=self.encoding ) File "/usr/lib/python2.4/site-packages/pyplusplus/file_writers/__init__.py", line 40, in write_file sf.write() File "/usr/lib/python2.4/site-packages/pyplusplus/file_writers/single_file.py", line 27, in write self.write_file( self.file_name, self.extmodule.create(), encoding=self.encoding ) File "/usr/lib/python2.4/site-packages/pyplusplus/file_writers/writer.py", line 124, in write_file f.write( unicode( fcontent_new, encoding ) ) TypeError: decoding Unicode is not supported Should I be writing the code generator from scratch? -Rob From matthew.scouten at gmail.com Tue Oct 2 18:47:41 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Tue, 2 Oct 2007 11:47:41 -0500 Subject: [C++-sig] Wrapping global data Message-ID: <3dc9bcf00710020947r231719c9u469de01e580f00f2@mail.gmail.com> OK, I can wrap a global function, I can wrap a member function, I can wrap a member variable, But I can't seem to figure out how to wrap a global variable. Maybe I'm just suffering from temporary stupidity. def_readonly() does not exist, def() results in hundreds of cryptic error messages that look like it is trying to wrap a function. From roman.yakovenko at gmail.com Tue Oct 2 20:52:49 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 2 Oct 2007 20:52:49 +0200 Subject: [C++-sig] Py++ question In-Reply-To: <3be982d00710020926v2b2885c4j68c4d2b25e3a9ab1@mail.gmail.com> References: <3be982d00710020926v2b2885c4j68c4d2b25e3a9ab1@mail.gmail.com> Message-ID: <7465b6170710021152o5bb101ffvfd1bb92852008990@mail.gmail.com> On 10/2/07, Robert O'Callahan wrote: > > I am trying to use a generate_code.py created by the py++ gui, but I > get this error: > > Traceback (most recent call last): > File "generate_code.py", line 40, in ? > export() > File "generate_code.py", line 37, in export > mb.write_module( os.path.join( settings.generated_files_dir, > settings.module_name + '.cpp') ) > File > "/usr/lib/python2.4/site-packages/pyplusplus/module_builder/builder.py", > line 311, in write_module > file_writers.write_file( self.code_creator, file_name, > encoding=self.encoding ) > File > "/usr/lib/python2.4/site-packages/pyplusplus/file_writers/__init__.py", > line 40, in write_file > sf.write() > File > "/usr/lib/python2.4/site-packages/pyplusplus/file_writers/single_file.py", > line 27, in write > self.write_file( self.file_name, self.extmodule.create(), > encoding=self.encoding ) > File > "/usr/lib/python2.4/site-packages/pyplusplus/file_writers/writer.py", > line 124, in write_file > f.write( unicode( fcontent_new, encoding ) ) > TypeError: decoding Unicode is not supported > > Should I be writing the code generator from scratch? What version of Py++ do you use? I fixed such error few weeks or month ago. Can you try SVN version? P.S. You will have to get SVN version of pygccxml too, but you can stay with your current version of GCC-XML -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Tue Oct 2 21:02:43 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 2 Oct 2007 21:02:43 +0200 Subject: [C++-sig] Wrapping global data In-Reply-To: <3dc9bcf00710020947r231719c9u469de01e580f00f2@mail.gmail.com> References: <3dc9bcf00710020947r231719c9u469de01e580f00f2@mail.gmail.com> Message-ID: <7465b6170710021202p116a5474ye9ec490981361c51@mail.gmail.com> On 10/2/07, Matthew Scouten wrote: > > OK, I can wrap a global function, I can wrap a member function, I can > wrap a member variable, The answer is: it depends * on global variable type * whether you need to share it between Python and C++ code at the same time for immutable types: http://boost.org/libs/python/doc/v2/scope.html for shared class instances: http://wiki.python.org/moin/boost.python/HowTo#head-85904d74f4f9f20c1380ede50e2eb95a4c333c37 P.S. Google will point you to other resources -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthew.scouten at gmail.com Tue Oct 2 22:20:45 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Tue, 2 Oct 2007 15:20:45 -0500 Subject: [C++-sig] Wrapping global data In-Reply-To: <7465b6170710021202p116a5474ye9ec490981361c51@mail.gmail.com> References: <3dc9bcf00710020947r231719c9u469de01e580f00f2@mail.gmail.com> <7465b6170710021202p116a5474ye9ec490981361c51@mail.gmail.com> Message-ID: <3dc9bcf00710021320h5e36131w3878d3bd6ef3dc20@mail.gmail.com> On 10/2/07, Roman Yakovenko wrote: > On 10/2/07, Matthew Scouten wrote: > > OK, I can wrap a global function, I can wrap a member function, I can > > wrap a member variable, > > The answer is: it depends > * on global variable type > * whether you need to share it between Python and C++ code at the same time > > for immutable types: > http://boost.org/libs/python/doc/v2/scope.html > > for shared class instances: > http://wiki.python.org/moin/boost.python/HowTo#head-85904d74f4f9f20c1380ede50e2eb95a4c333c37 > > P.S. Google will point you to other resources > Ah. From http://mail.python.org/pipermail/c++-sig/2003-June/004240.html it looks like what I thought I wanted to do is not possible. What I actually need to do is create a function that returns that variable in question. I would have thought that exposing a global variable directly would be a fairly obvious thing to do. Is there a reason that it is not possible? From roman.yakovenko at gmail.com Wed Oct 3 07:54:08 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Wed, 3 Oct 2007 07:54:08 +0200 Subject: [C++-sig] Wrapping global data In-Reply-To: <3dc9bcf00710021320h5e36131w3878d3bd6ef3dc20@mail.gmail.com> References: <3dc9bcf00710020947r231719c9u469de01e580f00f2@mail.gmail.com> <7465b6170710021202p116a5474ye9ec490981361c51@mail.gmail.com> <3dc9bcf00710021320h5e36131w3878d3bd6ef3dc20@mail.gmail.com> Message-ID: <7465b6170710022254r7e05482al559f96702ed484f3@mail.gmail.com> On 10/2/07, Matthew Scouten wrote: > > > > Ah. From > http://mail.python.org/pipermail/c++-sig/2003-June/004240.html > it looks like what I thought I wanted to do is not possible. What I > actually need to do is create a function that returns that variable in > question. I would have thought that exposing a global variable > directly would be a fairly obvious thing to do. Is there a reason that > it is not possible? > Hint: int is immutable type in Python -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From jumpjoe at fastwebnet.it Wed Oct 3 15:46:09 2007 From: jumpjoe at fastwebnet.it (Giovanni Beltrame) Date: Wed, 3 Oct 2007 15:46:09 +0200 Subject: [C++-sig] Boost.Python type registry Message-ID: <200710031546.09201.jumpjoe@fastwebnet.it> Hello everybody, I am trying to understand how the Boost.Python type registry works... What I want to do is, given a python object (let's say a PyObject*), determine its wrapper C++ type_info. Theoretically, what I want to do is going name->PyObject->C++ type. Notice that the traditional extract won't work for me as I want to determine which type is being wrapped. I know Boost.Python is doing this internally in some way, but I haven't figured it out yet. Can anybody help? Thanks in advance, -- Giovanni Beltrame TEC-EDM Research Fellow European Space Agency From duranlef at iro.umontreal.ca Wed Oct 3 22:31:33 2007 From: duranlef at iro.umontreal.ca (=?ISO-8859-1?Q?Fran=E7ois_Duranleau?=) Date: Wed, 3 Oct 2007 16:31:33 -0400 (EDT) Subject: [C++-sig] Boost.Python type registry In-Reply-To: <200710031546.09201.jumpjoe@fastwebnet.it> References: <200710031546.09201.jumpjoe@fastwebnet.it> Message-ID: On Wed, 3 Oct 2007, Giovanni Beltrame wrote: > Hello everybody, > I am trying to understand how the Boost.Python type registry works... > > What I want to do is, given a python object (let's say a PyObject*), determine > its wrapper C++ type_info. > Theoretically, what I want to do is going name->PyObject->C++ type. Notice > that the traditional extract won't work for me as I want to determine which > type is being wrapped. > > I know Boost.Python is doing this internally in some way, but I haven't > figured it out yet. > > Can anybody help? AFAIK, there is nothing in the API to help you there. Boost.Python doesn't work directly this way internally. It provides a way to test if an instance holds a given type, but nothing to return the contained type info. -- Francois Duranleau From pvicenti at gmail.com Thu Oct 4 00:14:48 2007 From: pvicenti at gmail.com (Paul Vicenti) Date: Wed, 3 Oct 2007 19:14:48 -0300 Subject: [C++-sig] Extansion compilation in Linux Message-ID: <531d9eef0710031514g3c49ebfax7b810af02f50f8f9@mail.gmail.com> Hi, I'm moving a project from Windows and I'm having problems to compile. I get a: 'undefined reference to 'PyThreadState_Get' and whatever I use in my code of Python library. In windows I include Python.h and it links with python library to resolve all symbols. Here, it looks that the include file is found (otherwise, I expect 'cannot open file Python.h') but the library seems not to be linked. Any help for this? thanks, paul From jumpjoe at fastwebnet.it Thu Oct 4 11:55:38 2007 From: jumpjoe at fastwebnet.it (jumpjoe at fastwebnet.it) Date: Thu, 4 Oct 2007 11:55:38 +0200 (CEST) Subject: [C++-sig] R: Re: Boost.Python type registry Message-ID: <33471873.346151191491738471.JavaMail.defaultUser@defaultHost> >AFAIK, there is nothing in the API to help you there. Boost.Python doesn't >work directly this way internally. It provides a way to test if an >instance holds a given type, but nothing to return the contained type >info. Is there at least a way to get a raw pointer to the wrapped object from a PyObject? I think extract<> is doing it. Cheers, Giovanni Beltrame From duranlef at iro.umontreal.ca Thu Oct 4 16:45:27 2007 From: duranlef at iro.umontreal.ca (=?ISO-8859-1?Q?Fran=E7ois_Duranleau?=) Date: Thu, 4 Oct 2007 10:45:27 -0400 (EDT) Subject: [C++-sig] Extansion compilation in Linux In-Reply-To: <531d9eef0710031514g3c49ebfax7b810af02f50f8f9@mail.gmail.com> References: <531d9eef0710031514g3c49ebfax7b810af02f50f8f9@mail.gmail.com> Message-ID: On Wed, 3 Oct 2007, Paul Vicenti wrote: > Hi, > I'm moving a project from Windows and I'm having problems to compile. I get a: > 'undefined reference to 'PyThreadState_Get' and whatever I use in my > code of Python library. > > In windows I include Python.h and it links with python library to > resolve all symbols. > Here, it looks that the include file is found (otherwise, I expect > 'cannot open file Python.h') but the library seems not to be linked. > > Any help for this? AFAIK, there is no auto-link feature with gcc. You need to tell it explicitly to link with the Python library by adding the swithc -lpython2.x (where x is the version you are using). -- Francois Duranleau From duranlef at iro.umontreal.ca Thu Oct 4 17:13:55 2007 From: duranlef at iro.umontreal.ca (=?ISO-8859-1?Q?Fran=E7ois_Duranleau?=) Date: Thu, 4 Oct 2007 11:13:55 -0400 (EDT) Subject: [C++-sig] R: Re: Boost.Python type registry In-Reply-To: <33471873.346151191491738471.JavaMail.defaultUser@defaultHost> References: <33471873.346151191491738471.JavaMail.defaultUser@defaultHost> Message-ID: On Thu, 4 Oct 2007, jumpjoe at fastwebnet.it wrote: >> AFAIK, there is nothing in the API to help you there. Boost.Python doesn't >> work directly this way internally. It provides a way to test if an >> instance holds a given type, but nothing to return the contained type >> info. > > Is there at least a way to get a raw pointer to the wrapped object from a > PyObject? I think extract<> is doing it. Neither. The only thing extract<> is "extracting" is the source object's type name as exposed to Python (obj->ob_type->tp_name where obj is a PyObject*) when reporting errors. Although with that you can maybe work something by registering an "inverse" mapping from Python type name to C++ type_info, but you would need to explicitly add entries to that registry each time you expose a class. -- Francois Duranleau From nickm at sitius.com Thu Oct 4 20:14:30 2007 From: nickm at sitius.com (Nikolay Mladenov) Date: Thu, 04 Oct 2007 14:14:30 -0400 Subject: [C++-sig] R: Re: Boost.Python type registry References: <33471873.346151191491738471.JavaMail.defaultUser@defaultHost> Message-ID: <47052D86.7795232C@sitius.com> I think that you can search the registry for entry with m_class_object that matches your PyObject's type or search the lvalue_chain(s) for a converter that returns !=0. But there is no api for that so far. HTH, Nikolay jumpjoe at fastwebnet.it wrote: > > >AFAIK, there is nothing in the API to help you there. Boost.Python doesn't > >work directly this way internally. It provides a way to test if an > >instance holds a given type, but nothing to return the contained type > >info. > > Is there at least a way to get a raw pointer to the wrapped object from a > PyObject? I think extract<> is doing it. > > Cheers, > Giovanni Beltrame From gtang at bcm.edu Fri Oct 5 00:36:12 2007 From: gtang at bcm.edu (Grant) Date: Thu, 04 Oct 2007 17:36:12 -0500 Subject: [C++-sig] inner class pickle issue Message-ID: I am trying to write pickle support for an inner class by using boost.pyhton. But it always fail with this error message: >>> pickle.dump(k,mm) Traceback (most recent call last): File "", line 1, in File "/usr/lib64/python2.5/pickle.py", line 1362, in dump Pickler(file, protocol).dump(obj) File "/usr/lib64/python2.5/pickle.py", line 224, in dump self.save(obj) File "/usr/lib64/python2.5/pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "/usr/lib64/python2.5/pickle.py", line 400, in save_reduce save(func) File "/usr/lib64/python2.5/pickle.py", line 295, in save self.save_global(obj) File "/usr/lib64/python2.5/pickle.py", line 748, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle : it's not found as libpyUtils2.KaiserBessel Can I pickle an inner class? Or only the top level class can be pickled? Grant From rwgk at yahoo.com Fri Oct 5 01:14:20 2007 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Thu, 4 Oct 2007 16:14:20 -0700 (PDT) Subject: [C++-sig] inner class pickle issue Message-ID: <351729.46895.qm@web31111.mail.mud.yahoo.com> > Or only the top level class can be pickled? Yes. Try this: import pickle class outer(object): class inner(object): pass oi = outer.inner() pickle.dumps(oi) You'll get a similar error message: pickle.PicklingError: Can't pickle : it's not found as __main__.inner Ralf From jumpjoe at fastwebnet.it Fri Oct 5 15:23:46 2007 From: jumpjoe at fastwebnet.it (jumpjoe at fastwebnet.it) Date: Fri, 5 Oct 2007 15:23:46 +0200 (CEST) Subject: [C++-sig] R: Re: R: Re: Boost.Python type registry Message-ID: <25216082.396051191590626009.JavaMail.defaultUser@defaultHost> >I think that you can search the registry for entry with m_class_object >that matches >your PyObject's type or search the lvalue_chain(s) for a converter that >returns !=0. >But there is no api for that so far. This is another interesting approach, but after a few tries, I discovered the registry is really hard to get by, as it is a static variable defined in a "hidden" function in an anonymous namespace in the registry.cpp file. Any suggestions on how to extract it? As an "extern" of some kind? Cheers, Giovanni Beltrame From duranlef at iro.umontreal.ca Fri Oct 5 17:22:20 2007 From: duranlef at iro.umontreal.ca (=?ISO-8859-1?Q?Fran=E7ois_Duranleau?=) Date: Fri, 5 Oct 2007 11:22:20 -0400 (EDT) Subject: [C++-sig] R: Re: R: Re: Boost.Python type registry In-Reply-To: <25216082.396051191590626009.JavaMail.defaultUser@defaultHost> References: <25216082.396051191590626009.JavaMail.defaultUser@defaultHost> Message-ID: On Fri, 5 Oct 2007, jumpjoe at fastwebnet.it wrote: >> I think that you can search the registry for entry with m_class_object >> that matches your PyObject's type or search the lvalue_chain(s) for a >> converter that returns !=0. But there is no api for that so far. > > This is another interesting approach, but after a few tries, I > discovered the registry is really hard to get by, as it is a static > variable defined in a "hidden" function in an anonymous namespace in the > registry.cpp file. Any suggestions on how to extract it? As an "extern" > of some kind? Without modifying the source code, there is no way. The only way to search the registry externally is via the boost::python::converter::query function, but then you need to provide a type_info, and to do this exhaustively is not really simpler than using an "inverse" registry like I mentionned. -- Francois Duranleau From rwgk at yahoo.com Fri Oct 5 20:46:26 2007 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Fri, 5 Oct 2007 11:46:26 -0700 (PDT) Subject: [C++-sig] R: Re: R: Re: Boost.Python type registry Message-ID: <858615.18297.qm@web31112.mail.mud.yahoo.com> Would it help you if you had an interface to extract an array of type_info objects known to the registry? If you send patches with docs I'll review them. BTW: What you need seems very unusual. Could you explain the situation? Did you consider alternative approaches? Ralf ----- Original Message ---- From: Fran?ois Duranleau To: jumpjoe at fastwebnet.it; Development of Python/C++ integration Sent: Friday, October 5, 2007 8:22:20 AM Subject: Re: [C++-sig] R: Re: R: Re: Boost.Python type registry On Fri, 5 Oct 2007, jumpjoe at fastwebnet.it wrote: >> I think that you can search the registry for entry with m_class_object >> that matches your PyObject's type or search the lvalue_chain(s) for a >> converter that returns !=0. But there is no api for that so far. > > This is another interesting approach, but after a few tries, I > discovered the registry is really hard to get by, as it is a static > variable defined in a "hidden" function in an anonymous namespace in the > registry.cpp file. Any suggestions on how to extract it? As an "extern" > of some kind? Without modifying the source code, there is no way. The only way to search the registry externally is via the boost::python::converter::query function, but then you need to provide a type_info, and to do this exhaustively is not really simpler than using an "inverse" registry like I mentionned. -- Francois Duranleau _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig From duranlef at iro.umontreal.ca Sat Oct 6 03:29:07 2007 From: duranlef at iro.umontreal.ca (=?ISO-8859-1?Q?Fran=E7ois_Duranleau?=) Date: Fri, 5 Oct 2007 21:29:07 -0400 (EDT) Subject: [C++-sig] R: Re: R: Re: Boost.Python type registry In-Reply-To: <858615.18297.qm@web31112.mail.mud.yahoo.com> References: <858615.18297.qm@web31112.mail.mud.yahoo.com> Message-ID: On Fri, 5 Oct 2007, Ralf W. Grosse-Kunstleve wrote: > Would it help you if you had an interface to extract an array of > type_info objects known to the registry? > If you send patches with docs I'll review them. > BTW: What you need seems very unusual. Could you explain the situation? > Did you consider alternative approaches? I don't know why the OP required this. I once thought it would be useful for implicit conversions to/from boost.function objects, but then I realized that even if you get the type_info, you still need to extract the object without having a (C++) type. So I ended up having to register manually an implicit conversion to/from boost.function for all exposed functors, which is not all that convenient. And I have yet to make this work for functions. -- Francois Duranleau From p.jaroszynski at gmail.com Sat Oct 6 18:59:23 2007 From: p.jaroszynski at gmail.com (Piotr =?utf-8?q?Jaroszy=C5=84ski?=) Date: Sat, 6 Oct 2007 18:59:23 +0200 Subject: [C++-sig] Multiple-inheritance problem Message-ID: <200710061859.24313.p.jaroszynski@gmail.com> Hello, Seems that when one creates a Python class, which multiple-inherits from classes exposed by boost.python then it can be only converted(casted) to the first class in the inheritance list. Simple example code follows. C++: #include namespace bp = boost::python; struct A { }; struct B { }; void test_A(const A &) { } void test_B(const B &) { } BOOST_PYTHON_MODULE(multiple_inheritance) { bp::def("test_A", &test_A); bp::def("test_B", &test_B); bp::class_("A", bp::init<>()); bp::class_("B", bp::init<>()); } Python: class C(A, B): pass test_A(C()) test_B(C()) And I get: Traceback (most recent call last): File "./multiple_inheritance.py", line 10, in test_B(C()) Boost.Python.ArgumentError: Python argument types in multiple_inheritance.test_B(C) did not match C++ signature: test_B(B) Am I missing something or is it a known problem? Any workaround if so? -- Best Regards, Piotr Jaroszy?ski From jumpjoe at fastwebnet.it Mon Oct 8 10:48:07 2007 From: jumpjoe at fastwebnet.it (Giovanni Beltrame) Date: Mon, 8 Oct 2007 10:48:07 +0200 Subject: [C++-sig] Re: Boost.Python type registry In-Reply-To: <858615.18297.qm@web31112.mail.mud.yahoo.com> References: <858615.18297.qm@web31112.mail.mud.yahoo.com> Message-ID: <200710081048.07356.jumpjoe@fastwebnet.it> On Friday 05 October 2007 20:46:26 Ralf W. Grosse-Kunstleve wrote: > BTW: What you need seems very unusual. Could you explain the situation? > Did you consider alternative approaches? The situation is definitely unusual, but I will try to explain. I have a simulator that uses a C++ kernel and a bunch of simulation components. Now I want to wrap both kernel and components and add scripting and inspection functionality in Python. Python will be used to instantiate the simulation components and run what I will call the "architecture". So far, so good, I have everything wrapped. The problem is that I might want to debug the architecture. I was thinking of using GDB, but since components are instantiated in Python (note that I might have more objects that belong to one class), it is hard to get a reference to them. Setting a breakpoint on the source code is be easy, but putting a watch on a variable is much more tricky. In the end what I would like to have is a sort of python-controlled GDB breakpoint mechanism, where I set a condition in python and C++ is stopped when the condition arises. Getting a reference to the object/variable should be enough to put a watch in GDB (and here's why I'm trying to pass from PyObject to the C++ address). Any suggestion is welcome! -- Giovanni Beltrame TEC-EDM Research Fellow European Space Agency From ndbecker2 at gmail.com Tue Oct 9 21:02:27 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 09 Oct 2007 15:02:27 -0400 Subject: [C++-sig] interaction of boost::shared_ptr with boost::python Message-ID: A bit puzzled about this one. struct X { X() { std::cout << "X()" << '\n'; } ~X() { std::cout << "~X()" << '\n'; } }; boost::shared_ptr make_x () { return boost::shared_ptr (new X); } boost::shared_ptr make_x_from_shared (boost::shared_ptr x) { return boost::shared_ptr (new X); } X* clone1 (X const& x) { return new X; } boost::shared_ptr clone2 (X const& x) { return boost::shared_ptr (new X); } BOOST_PYTHON_MODULE (stuff) { class_ ("X", no_init) .def ("__init__", make_constructor (make_x)) .def ("__init__", make_constructor (make_x_from_shared)) .def ("__copy__", &clone1, return_value_policy()) .def ("__copy2__", &clone2) ; def ("clone1", &clone1, return_value_policy()); def ("clone2", &clone2); >>> x = X() >>> clone2(x) Traceback (most recent call last): File "", line 1, in TypeError: No to_python (by-value) converter found for C++ type: boost::shared_ptr From ndbecker2 at gmail.com Wed Oct 10 20:54:25 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 10 Oct 2007 14:54:25 -0400 Subject: [C++-sig] No registered converter was able to produce a C++ rvalue... Message-ID: I know this comes up frequently, but this one has me baffled. u = array1_complex_int ((1,2)) TypeError: No registered converter was able to produce a C++ rvalue of type std::complex from this Python object of type int But there is a converter, it can be invoked from the python side: >>> complex_int (2) or like this: u = array1_complex_int (complex_int(e) for e in (1,2)) It seems that extract > is not finding the conversion. Any hints? The conversion is there, because there is this minimal class_: bp::class_ > ("complex_int", bp::init >()) ; From seefeld at sympatico.ca Wed Oct 10 21:08:40 2007 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Wed, 10 Oct 2007 15:08:40 -0400 Subject: [C++-sig] PyObject_Call() wrapper ? Message-ID: <470D2338.7020004@sympatico.ca> I'm looking for the boost.python equivalent of the generic callable(*args, **kwds) i.e. a version of the call operator that takes an arguments vector as well as a keyword dictionary, instead of individual arguments. I can't find it. Is that not implemented ? May I submit a patch for it ? Thanks, Stefan -- ...ich hab' noch einen Koffer in Berlin... From amohr at pixar.com Wed Oct 10 22:28:58 2007 From: amohr at pixar.com (Alex Mohr) Date: Wed, 10 Oct 2007 13:28:58 -0700 Subject: [C++-sig] PyObject_Call() wrapper ? In-Reply-To: <470D2338.7020004@sympatico.ca> References: <470D2338.7020004@sympatico.ca> Message-ID: <470D360A.8040508@pixar.com> > I'm looking for the boost.python equivalent of the generic > > callable(*args, **kwds) > > i.e. a version of the call operator that takes an arguments vector > as well as a keyword dictionary, instead of individual arguments. > I can't find it. Is that not implemented ? May I submit > a patch for it ? I implemented this by overloading unary * so that in boost python you could actually write what you wrote above. David A. signed off on the idea so I think he'd welcome a patch. Unfortunately I never got permission from my employer to post my patch. I think it would be awesome if you did it -- I think these are the cases: object(a1, a2 .. aN) object(a1, a2 .. aN, *args) object(a1, a2 .. aN, **kw) object(a1, a2 .. aN, *args, **kw) Alex From steven.wyckoff at gmail.com Wed Oct 10 23:53:06 2007 From: steven.wyckoff at gmail.com (Steven Wyckoff) Date: Wed, 10 Oct 2007 15:53:06 -0600 Subject: [C++-sig] convert child class to child class {lvalue} ? Message-ID: Hi all, I am trying to wrap some C++ code that involves an object factory and manager and I seem to be stumped by how boost is converting types. I have a base class and a few classes that inherit from it and a factory to create instances of these classes. Using the factory I can successfully create objects of the proper type. Following the tutorial I have virtual functions behaving properly. However, if I try to call methods that only exist in a child class, I get an Argument Error: ArgumentError: Python argument types in childobj.ChildOnly(childobj) did not match C++ signature: ChildOnly(struct childobj {lvalue}) I have tried writing a function that will cast the pointer to a child class pointer. This lets me call child only methods, but then i get the mirror error when I try to call base class methods. The confounding part is that it appears that the type information is correct in python. If I create an instance without using the factory (child = childobj()) then everything works just fine. I guess I could write converters to go both ways and just cast to whatever type I need for the current function call, but that is hardly ideal. If anyone has any suggestions about how I can get around this (maybe a type converter that I'm not aware of?) I would appreciate it. Here is my code: C++ code: ----------------------------------------------------------------------- struct baseobj { virtual std::string ID() {return std::string("BaseObj");} void SetVal(int v) {val = v;} int GetVal() {return val;} int val; }; struct childobj : public baseobj { virtual std::string ID() {return std::string("ChildObj");} std::string ChildOnly() {return "OK";} }; baseobj* createobj(std::string kind) { if(kind == "Base") { return new baseobj(); } else if(kind == "Child") { return new childobj(); } else { return NULL; } } childobj* CastToChild(baseobj* pobj) { return static_cast(pobj); } struct BaseWrap : baseobj, boost::python::wrapper { std::string ID() { if(boost::python::override f = this->get_override("ID")) return ID(); return baseobj::ID(); } std::string default_ID() {return this->baseobj::ID();} }; BOOST_PYTHON_MODULE(extending) { using namespace boost::python; class_("baseobj") .def("ID", &baseobj::ID, &BaseWrap::ID, "Returns the ID of the object") .def("GetVal", &baseobj::GetVal) .def("SetVal", &baseobj::SetVal) ; class_ >("childobj") .def("ChildOnly", &childobj::ChildOnly) ; implicitly_convertible(); class_("objman") .def("SetObj", &objman::SetObj) .def("GetObj", &objman::GetObj, return_value_policy()) ; def("create", &createobj, return_value_policy() ); def("callID", &callID ); def("CastToChild", &CastToChild, return_value_policy()); } Python: ---------------------------------------------------------------------------- >>> from extending import * >>> base = create("Base") >>> base.ID() 'BaseObj' >>> child = create("Child") >>> child.ID() 'ChildObj' >>> child.ChildOnly() Traceback (most recent call last): File "", line 1, in child.ChildOnly() ArgumentError: Python argument types in childobj.ChildOnly(childobj) did not match C++ signature: ChildOnly(struct childobj {lvalue}) >>> castchild = CastToChild(child) >>> castchild.ChildOnly() 'OK' >>> castchild.ID() Traceback (most recent call last): File "", line 1, in castchild.ID() ArgumentError: Python argument types in baseobj.ID(childobj) did not match C++ signature: ID(struct BaseWrap {lvalue}) ID(struct baseobj {lvalue}) From Chang_Chen at sonic.com Thu Oct 11 07:44:52 2007 From: Chang_Chen at sonic.com (Chang Chen) Date: Thu, 11 Oct 2007 13:44:52 +0800 Subject: [C++-sig] Can boost python do these 2 things automatically? Message-ID: <51C471E6CBEC8148A08E065690F4DBDF0160033A@SHAEXC01.ent.sonic.com> Hi All I am new to boost python. I have 2 questions for using boost python to wrap C++ API Our C++ API looks like this: class BImpl; Class B { public: B(){} Error DoSomething(); private: BImpl*; mpBImpl } class A { public: A(){} Error CreateB(B& bObj); private: ... } Our error handle strategy is returning an error code other than throwing exception. This is because throwing an exception across the DLL boundary is not safe. I want to wrap A and B with same C++ public interface in python, but #1 I want to return real object rather than return an error code. i.e. in python aObject = A() *bObject = aObject.CreateB()* #2 I want to throw an *python* exception rather than return an error code like c++. I do not know how to do it in Boost Python. Any suggestion? Chang -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mark.English at rbccm.com Thu Oct 11 09:44:35 2007 From: Mark.English at rbccm.com (English, Mark) Date: Thu, 11 Oct 2007 08:44:35 +0100 Subject: [C++-sig] convert child class to child class {lvalue} ? Message-ID: > -----Original Message----- > From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org]On > Behalf Of Steven Wyckoff > Sent: 10 October 2007 22:53 > To: c++-sig at python.org > Subject: [C++-sig] convert child class to child class {lvalue} ? > > > Hi all, > > I am trying to wrap some C++ code that involves an object factory and > manager and I seem to be stumped by how boost is converting > types. > baseobj* createobj(std::string kind) > { > if(kind == "Base") > { > return new baseobj(); > } > else if(kind == "Child") > { > return new childobj(); > } > else > { > return NULL; > } > } Haven't tested this myself, but try something like: ---C++ code--- boost::shared_ptr createobj(std::string kind) { boost::shared_ptr ptrCreate; if(kind == "Base") { ptrCreate = new baseobj; } else if(kind == "Child") { ptrCreate = new childobj; } else { ptrCreate = NULL; } return ptrCreate; } ________________________________________ This E-Mail (including any attachments) may contain privileged or confidential information. It is intended only for the addressee(s) indicated above. The sender does not waive any of its rights, privileges or other protections respecting this information. Any distribution, copying or other use of this E-Mail or the information it contains, by other than an intended recipient, is not sanctioned and is prohibited. If you received this E-Mail in error, please delete it and advise the sender (by return E-Mail or otherwise) immediately. This E-Mail (including any attachments) has been scanned for viruses. It is believed to be free of any virus or other defect that might affect any computer system into which it is received and opened. However, it is the responsibility of the recipient to ensure that it is virus free. The sender accepts no responsibility for any loss or damage arising in any way from its use. E-Mail received by or sent from RBC Capital Markets is subject to review by Supervisory personnel. Such communications are retained and may be produced to regulatory authorities or others with legal rights to the information. IRS CIRCULAR 230 NOTICE: TO COMPLY WITH U.S. TREASURY REGULATIONS, WE ADVISE YOU THAT ANY U.S. FEDERAL TAX ADVISE INCLUDED IN THIS COMMUNICATION IS NOT INTENDED OR WRITTEN TO BE USED, AND CANNOT BE USED, TO AVOID ANY U.S. FEDERAL TAX PENALTIES OR TO PROMOTE, MARKET, OR RECOMMEND TO ANOTHER PARTY ANY TRANSACTION OR MATTER. From Chang_Chen at sonic.com Thu Oct 11 10:58:30 2007 From: Chang_Chen at sonic.com (Chang Chen) Date: Thu, 11 Oct 2007 16:58:30 +0800 Subject: [C++-sig] Can boost python do these 2 things automatically? Message-ID: <51C471E6CBEC8148A08E065690F4DBDF016003FC@SHAEXC01.ent.sonic.com> Hi All I am new to boost python. I have 2 questions for using boost python to wrap C++ API Our C++ API looks like this: class BImpl; Class B { ? public: ?? B(){} ?? Error DoSomething(); private: ? BImpl*; mpBImpl???????? } class A { ? public: ?? A(){} ?? Error CreateB(B& bObj); ? private: ??? ... } Our error handle strategy is returning an error code other than throwing exception. This is because throwing an exception across the DLL boundary is not safe. I want to wrap A and B with same C++ public interface in python, but #1 I want to return real object rather than retrieve object. i.e. in python, I would like users writing code like this: aObject = A() ~bObject = aObject.CreateB()~ #2 I want to throw an *python* exception rather than return an error code like c++. I do not know how to do it in Boost Python. Any suggestion? Chang From j.reid at mail.cryst.bbk.ac.uk Thu Oct 11 12:05:16 2007 From: j.reid at mail.cryst.bbk.ac.uk (John Reid) Date: Thu, 11 Oct 2007 11:05:16 +0100 Subject: [C++-sig] Raoul Gough's container suite with svn boost-trunk boost.python? Message-ID: Has anyone tried using Raoul's container suite with the svn boost-trunk? I'm getting the following error: C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(236) : error C2903: 'extract_return_type' : symbol is neither a class template nor a function template C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(232) : while compiling class template member function 'boost::python::detail::py_func_sig_info boost::python::detail::caller_arity<2>::impl::signature(void)' with [ F=boost::python::list (__cdecl *)(std::vector &,boost::python::indexing::slice), Policies=boost::python::indexing::detail::postcall_override, Sig=boost::mpl::vector3 &,boost::python::indexing::slice> ] So the problem seems to be there is no extract_return_type in boost::python::indexing::detail::postcall_override If I remember correctly, I've installed Roman's version by copying it into boost/python/suite/indexing John. From meine at informatik.uni-hamburg.de Thu Oct 11 13:01:12 2007 From: meine at informatik.uni-hamburg.de (Hans Meine) Date: Thu, 11 Oct 2007 13:01:12 +0200 Subject: [C++-sig] convert child class to child class {lvalue} ? In-Reply-To: References: Message-ID: <200710111301.12681.meine@informatik.uni-hamburg.de> Am Mittwoch, 10. Oktober 2007 23:53:06 schrieb Steven Wyckoff: > BOOST_PYTHON_MODULE(extending) > { > using namespace boost::python; > > class_("baseobj") > .def("ID", &baseobj::ID, &BaseWrap::ID, "Returns the ID of the object") > .def("GetVal", &baseobj::GetVal) > .def("SetVal", &baseobj::SetVal) > ; > > class_ >("childobj") > .def("ChildOnly", &childobj::ChildOnly) > ; I never used wrapper<>, but did you try bases? I mean - childobj *is* derived from baseobj, not BaseWrap. -- Ciao, / / /--/ / / ANS From nickm at sitius.com Thu Oct 11 18:20:07 2007 From: nickm at sitius.com (Nikolay Mladenov) Date: Thu, 11 Oct 2007 12:20:07 -0400 Subject: [C++-sig] Raoul Gough's container suite with svn boost-trunkboost.python? References: Message-ID: <470E4D37.5B9DE011@sitius.com> This error is related to the documentation patch which I recently submited. I will look into it. Nikolay John Reid wrote: > > Has anyone tried using Raoul's container suite with the svn boost-trunk? > > I'm getting the following error: > > C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(236) > : error C2903: 'extract_return_type' : symbol is neither a class > template nor a function template > > C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(232) > : while compiling class template member function > 'boost::python::detail::py_func_sig_info > boost::python::detail::caller_arity<2>::impl::signature(void)' > with > [ > F=boost::python::list (__cdecl > *)(std::vector &,boost::python::indexing::slice), > > Policies=boost::python::indexing::detail::postcall_override, > > Sig=boost::mpl::vector3 > &,boost::python::indexing::slice> > ] > > So the problem seems to be there is no extract_return_type in > boost::python::indexing::detail::postcall_override > > If I remember correctly, I've installed Roman's version by copying it > into boost/python/suite/indexing > > John. From steven.wyckoff at gmail.com Thu Oct 11 18:32:19 2007 From: steven.wyckoff at gmail.com (Steven Wyckoff) Date: Thu, 11 Oct 2007 10:32:19 -0600 Subject: [C++-sig] convert child class to child class {lvalue} ? In-Reply-To: <200710111301.12681.meine@informatik.uni-hamburg.de> References: <200710111301.12681.meine@informatik.uni-hamburg.de> Message-ID: Hans Meine wrote: > Am Mittwoch, 10. Oktober 2007 23:53:06 schrieb Steven Wyckoff: >> BOOST_PYTHON_MODULE(extending) >> { >> using namespace boost::python; >> >> class_("baseobj") >> .def("ID", &baseobj::ID, &BaseWrap::ID, "Returns the ID of the object") >> .def("GetVal", &baseobj::GetVal) >> .def("SetVal", &baseobj::SetVal) >> ; >> >> class_ >("childobj") >> .def("ChildOnly", &childobj::ChildOnly) >> ; > > I never used wrapper<>, but did you try bases? > I mean - childobj *is* derived from baseobj, not BaseWrap. > That was it! That was the sneaky, silly thing I was doing wrong that broke everything. Switching to bases seems to let boost cast properly when legal just as one would expect it should. Thanks for the help! Steven From seefeld at sympatico.ca Thu Oct 11 19:09:21 2007 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 11 Oct 2007 13:09:21 -0400 Subject: [C++-sig] PyObject_Call() wrapper ? In-Reply-To: <470D360A.8040508@pixar.com> References: <470D2338.7020004@sympatico.ca> <470D360A.8040508@pixar.com> Message-ID: <470E58C1.3040008@sympatico.ca> Alex Mohr wrote: >> I'm looking for the boost.python equivalent of the generic >> >> callable(*args, **kwds) [...] > I think it would be awesome if you did it -- I think these are the cases: I just submitted a patch: http://svn.boost.org/trac/boost/ticket/1316 Reviews are highly welcome, especially from Dave. :-) > object(a1, a2 .. aN) > object(a1, a2 .. aN, *args) > object(a1, a2 .. aN, **kw) > object(a1, a2 .. aN, *args, **kw) While these could all be implemented, the only one directly supported by the Python C API (PyObject_Call()) is the one with N==0, i.e. object(*args, **kw), so this is what my patch includes. Anything else requires to manually rebuild the argument vector before passing it down. (As a cosmetic point: I'm not sure whether the code layout is ideal. It may be better to put the additions into a separate file. Dave ?) Regards, Stefan -- ...ich hab' noch einen Koffer in Berlin... From amohr at pixar.com Thu Oct 11 19:33:41 2007 From: amohr at pixar.com (Alex Mohr) Date: Thu, 11 Oct 2007 10:33:41 -0700 Subject: [C++-sig] PyObject_Call() wrapper ? In-Reply-To: <470E58C1.3040008@sympatico.ca> References: <470D2338.7020004@sympatico.ca> <470D360A.8040508@pixar.com> <470E58C1.3040008@sympatico.ca> Message-ID: <470E5E75.9040309@pixar.com> > I just submitted a patch: > > http://svn.boost.org/trac/boost/ticket/1316 > > Reviews are highly welcome, especially from Dave. :-) Cool! >> object(a1, a2 .. aN) >> object(a1, a2 .. aN, *args) >> object(a1, a2 .. aN, **kw) >> object(a1, a2 .. aN, *args, **kw) > > While these could all be implemented, the only one directly supported > by the Python C API (PyObject_Call()) is the one with N==0, i.e. > object(*args, **kw), so this is what my patch includes. Anything else > requires to manually rebuild the argument vector before passing it down. I think they should all be implemented because boost.python's c++ api is meant to let you write c++ code that is as similar as possible to python. I find this to be one of the great features of boost.python. Alex From nickm at sitius.com Thu Oct 11 21:01:18 2007 From: nickm at sitius.com (Nikolay Mladenov) Date: Thu, 11 Oct 2007 15:01:18 -0400 Subject: [C++-sig] Raoul Gough's container suite with svn boost-trunkboost.python? References: Message-ID: <470E72FE.48A19C6D@sitius.com> I found it, the postcall_override template needs to have the following line typedef typename Policy::extract_return_type extract_return_type; HTH, Nikolay John Reid wrote: > > Has anyone tried using Raoul's container suite with the svn boost-trunk? > > I'm getting the following error: > > C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(236) > : error C2903: 'extract_return_type' : symbol is neither a class > template nor a function template > > C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(232) > : while compiling class template member function > 'boost::python::detail::py_func_sig_info > boost::python::detail::caller_arity<2>::impl::signature(void)' > with > [ > F=boost::python::list (__cdecl > *)(std::vector &,boost::python::indexing::slice), > > Policies=boost::python::indexing::detail::postcall_override, > > Sig=boost::mpl::vector3 > &,boost::python::indexing::slice> > ] > > So the problem seems to be there is no extract_return_type in > boost::python::indexing::detail::postcall_override > > If I remember correctly, I've installed Roman's version by copying it > into boost/python/suite/indexing > > John. From nickm at sitius.com Thu Oct 11 19:50:57 2007 From: nickm at sitius.com (Nikolay Mladenov) Date: Thu, 11 Oct 2007 13:50:57 -0400 Subject: [C++-sig] Raoul Gough's container suite with svn boost-trunkboost.python? References: Message-ID: <470E6281.ACED5B86@sitius.com> Hi John, I could not find the class postcall_override. Can you give me a pointer? By "Roman's version", do you mean the files that come with py++? Nikolay John Reid wrote: > > Has anyone tried using Raoul's container suite with the svn boost-trunk? > > I'm getting the following error: > > C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(236) > : error C2903: 'extract_return_type' : symbol is neither a class > template nor a function template > > C:\Dev\ThirdParty\boost\boost-trunk\boost/python/detail/caller.hpp(232) > : while compiling class template member function > 'boost::python::detail::py_func_sig_info > boost::python::detail::caller_arity<2>::impl::signature(void)' > with > [ > F=boost::python::list (__cdecl > *)(std::vector &,boost::python::indexing::slice), > > Policies=boost::python::indexing::detail::postcall_override, > > Sig=boost::mpl::vector3 > &,boost::python::indexing::slice> > ] > > So the problem seems to be there is no extract_return_type in > boost::python::indexing::detail::postcall_override > > If I remember correctly, I've installed Roman's version by copying it > into boost/python/suite/indexing > > John. From j.reid at mail.cryst.bbk.ac.uk Fri Oct 12 08:49:44 2007 From: j.reid at mail.cryst.bbk.ac.uk (John Reid) Date: Fri, 12 Oct 2007 07:49:44 +0100 Subject: [C++-sig] Raoul Gough's container suite with svn boost-trunkboost.python? In-Reply-To: <470E6281.ACED5B86@sitius.com> References: <470E6281.ACED5B86@sitius.com> Message-ID: Nikolay Mladenov wrote: > Hi John, > > I could not find the class postcall_override. Can you give me a pointer? > By "Roman's version", do you mean the files that come with py++? > Yes. If I remember correctly they were taken from the py++ SVN repository. I can try and check later. From matthew.scouten at gmail.com Fri Oct 12 18:18:30 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Fri, 12 Oct 2007 11:18:30 -0500 Subject: [C++-sig] wrapping a function that takes a void* Message-ID: <3dc9bcf00710120918w639580cas574390c07b10d354@mail.gmail.com> I am wraping a function that takes a void* as an argument. class Special { int fooRequest(void * userData = NULL); virtual void fooCallback(void * userData) } The intention is that the user data pointer will be returned to 'remind' the program what callback goes with what request. my first attempt: struct Special_wrapper: Special, wrapper { int fooRequest(PyObject * userData = NULL); } int Special_wrapper::fooRequest(PyObject * userData) { return fooRequest((void*) userData) } and later class("Special") .def("fooRequest" ,&Special_wrapper::fooRequest ,(arg("userData") = (void*)NULL)) I get a error the first line of which is: C:\Documents and Settings\mscouten\Desktop\boost_1_32_0\boost_1_32_0\boost/python/converter/arg_to_python.hpp(181) : error C2027: use of undefined type 'boost::python::converter::detail::cannot_convert_raw_PyObject' (Full error text available on request) Does any body have any recommendations about how I could wrap this. From Mark.English at rbccm.com Fri Oct 12 18:33:55 2007 From: Mark.English at rbccm.com (English, Mark) Date: Fri, 12 Oct 2007 17:33:55 +0100 Subject: [C++-sig] wrapping a function that takes a void* Message-ID: X-Replace-Address: mark.ignorethisbit.english at xxxrbccmxxx.ignorethisbittoo_and_removethosepreceding_xxxs_.com > -----Original Message----- > From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org]On > Behalf Of Matthew Scouten > Sent: 12 October 2007 17:19 > To: Development of Python/C++ integration > Subject: [C++-sig] wrapping a function that takes a void* > > > I am wraping a function that takes a void* as an argument. Is an opaque pointer what you're looking for ? http://www.boost.org/libs/python/doc/v2/return_opaque_pointer.html Note there are some potential bugs in this. The PyTypeObject's name causes a crash I believe but I'm using boost 1.32, Python 2.3.6 so it may have been fixed by now in either of those. For example using the example code: >>> import opaque_ext >>> p = opaque_ext.get() >>> type(p) #Causes an access violation Cheers, mE ______________________________________________________________________ This email is intended only for the use of the individual(s) to whom it is addressed and may be privileged and confidential. Unauthorised use or disclosure is prohibited.If you receive This e-mail in error, please advise immediately and delete the original message. This message may have been altered without your or our knowledge and the sender does not accept any liability for any errors or omissions in the message. From matthew.scouten at gmail.com Fri Oct 12 18:44:59 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Fri, 12 Oct 2007 11:44:59 -0500 Subject: [C++-sig] wrapping a function that takes a void* In-Reply-To: References: Message-ID: <3dc9bcf00710120944i72b3be5dva66634080d825a01@mail.gmail.com> On 10/12/07, English, Mark wrote: > X-Replace-Address: mark.ignorethisbit.english at xxxrbccmxxx.ignorethisbittoo_and_removethosepreceding_xxxs_.com > > -----Original Message----- > > From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org]On > > Behalf Of Matthew Scouten > > Sent: 12 October 2007 17:19 > > To: Development of Python/C++ integration > > Subject: [C++-sig] wrapping a function that takes a void* > > > > > > I am wraping a function that takes a void* as an argument. > Is an opaque pointer what you're looking for ? > http://www.boost.org/libs/python/doc/v2/return_opaque_pointer.html > > Note there are some potential bugs in this. The PyTypeObject's name causes a crash I believe but I'm using boost 1.32, Python 2.3.6 so it may have been fixed by now in either of those. > For example using the example code: > >>> import opaque_ext > >>> p = opaque_ext.get() > >>> type(p) #Causes an access violation > > Cheers, > mE No, I need the opposite of that. I have a reference to some python object (any python object) that needs to be passed to a c++ function expecting a (void *). Later, that object will be handed back to python as a reference again. It is fine to tell the python programmer that it is his problem to prevent the object from being GCed in the meantime. From Mark.English at rbccm.com Fri Oct 12 18:47:49 2007 From: Mark.English at rbccm.com (English, Mark) Date: Fri, 12 Oct 2007 17:47:49 +0100 Subject: [C++-sig] wrapping a function that takes a void* Message-ID: X-Replace-Address: mark.ignorethisbit.english at xxxrbccmxxx.ignorethisbittoo_and_removethosepreceding_xxxs_.com > No, I need the opposite of that. I have a reference to some python > object (any python object) that needs to be passed to a c++ function > expecting a (void *). Later, that object will be handed back to python > as a reference again. Ok. How about: int Special_wrapper::fooRequest(boost::python::object objUserData) { return fooRequest((void*) objUserData.ptr()); } ______________________________________________________________________ This email is intended only for the use of the individual(s) to whom it is addressed and may be privileged and confidential. Unauthorised use or disclosure is prohibited.If you receive This e-mail in error, please advise immediately and delete the original message. This message may have been altered without your or our knowledge and the sender does not accept any liability for any errors or omissions in the message. From matthew.scouten at gmail.com Fri Oct 12 21:02:59 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Fri, 12 Oct 2007 14:02:59 -0500 Subject: [C++-sig] wrapping a function that takes a void* In-Reply-To: References: Message-ID: <3dc9bcf00710121202h478284a7lcab1dfd1b54e3313@mail.gmail.com> On 10/12/07, English, Mark wrote: > X-Replace-Address: mark.ignorethisbit.english at xxxrbccmxxx.ignorethisbittoo_and_removethosepreceding_xxxs_.com > > No, I need the opposite of that. I have a reference to some python > > object (any python object) that needs to be passed to a c++ function > > expecting a (void *). Later, that object will be handed back to python > > as a reference again. > > Ok. How about: > int Special_wrapper::fooRequest(boost::python::object objUserData) > { > return fooRequest((void*) objUserData.ptr()); > } Ok, that looks sane. two questions though: 1) I assume I get the 'object' back with ' object o(p) ' where is a void pointer? 2) how do I handle the default argument? the export used to be .def("fooRequest" ,&Special_wrapper::fooRequest ,(arg("userData") = (void*)NULL)) Can I get a None to use in place of that NULL? From simon at dackbrann.net Sun Oct 14 16:55:29 2007 From: simon at dackbrann.net (Simon Norberg) Date: Sun, 14 Oct 2007 16:55:29 +0200 Subject: [C++-sig] access struct inside class Message-ID: <47122DE1.3050801@dackbrann.net> Hello, im trying to get python to read and write to a struct inside a class in the same way i do in c++ Customers hej; hej.address.contact = "The Devil"; but i cant even get the code to compile, any suggestions? #include #include using namespace std; class Customers { private: struct s_address { string contact; string street1; string street2; string city; string province; string postalCode; string country; }; public: s_address address; Customers(){} ~Customers(){} }; #include #include #include #include #include using namespace boost::python; BOOST_PYTHON_MODULE(test) { scope outer= class_("Customers") ; class_("address") .def_readwrite("contact", &Customers::address.contact) ; } When i compile i get this error: test.cpp: In function ?void init_module_test()?: test.cpp:36: error: ?Customers::address? cannot appear in a constant-expression test.cpp:36: error: template argument 1 is invalid test.cpp:18: error: invalid use of non-static data member ?Customers::address? test.cpp:37: error: from this location what i want to be able to do in python is from test import * cust = Customers() cust.address.contact = "Hello" print cust.address.contact From nico_ml at mgdesign.fr Mon Oct 15 19:09:53 2007 From: nico_ml at mgdesign.fr (Nicolas Lelong) Date: Mon, 15 Oct 2007 19:09:53 +0200 Subject: [C++-sig] access struct inside class References: <47122DE1.3050801@dackbrann.net> Message-ID: <00d701c80f4e$3458a6f0$dd00a8c0@shreider> Hello, it should be &Customers::address::contact not &Customers::address.contact ... From grh at mur.at Mon Oct 15 20:07:37 2007 From: grh at mur.at (Georg Holzmann) Date: Mon, 15 Oct 2007 20:07:37 +0200 Subject: [C++-sig] datastructure to numpy and back Message-ID: <4713AC69.4000804@mur.at> Hallo! I know this was discussed quite some times, but I did find that many workarounds and not really a common way how to do that with Boost.Python ... so I am a little bit confused ... My problem: I have a class with some (big) custom C++ matrix types and I want to write some getters/setters for them to/from numpy arrays, where I want to avoid copies of the data. So is there a common way to do this ? (e.g. num_util from http://www.eos.ubc.ca/research/clouds/software/pythonlibs/num_util/num_util_release2/Readme.html ?) Or can maybe someone link me to some docu or examples which already did this ? (it must be quite common ...) Many thanks for any hint, LG Georg From simon at dackbrann.net Mon Oct 15 20:48:53 2007 From: simon at dackbrann.net (Simon Norberg) Date: Mon, 15 Oct 2007 20:48:53 +0200 Subject: [C++-sig] access struct inside class In-Reply-To: <00d701c80f4e$3458a6f0$dd00a8c0@shreider> References: <47122DE1.3050801@dackbrann.net> <00d701c80f4e$3458a6f0$dd00a8c0@shreider> Message-ID: <4713B615.2070805@dackbrann.net> Hello Thanks for ypur replay whit your proposed change i get: test.cpp: In function ?void init_module_test()?: test.cpp:36: error: ?Customers::address? cannot appear in a constant-expression test.cpp:36: error: template argument 1 is invalid test.cpp:37: error: ?class Customers::address? is not a class or namespace error: command 'gcc' failed with exit status 1 make: *** [default] Fel 1 one error down 3 more to go Nicolas Lelong wrote: > Hello, > > it should be > > &Customers::address::contact > > not > > &Customers::address.contact > > ... > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > > From candace_walker at naughtydog.com Mon Oct 15 22:31:23 2007 From: candace_walker at naughtydog.com (Candace Walker) Date: Mon, 15 Oct 2007 13:31:23 -0700 Subject: [C++-sig] Programmer Search @ Naughty Dog! Message-ID: <002f01c80f6a$5b86a580$09c9a8c0@DAMLT1> Hi Hamilton, My name is Candace Walker and I am the recruiter at Naughty Dog in Santa Monica, CA. Naughty Dog is owned by Sony Computer Entertainment of America and is developer of the Crash Bandicoot and Jak and Daxter franchises. I wanted to reach out to you and let you Naughty Dog is active to staff up for solid engineers. Naughty Dog has two teams right now, our Game Team and our ICE Team. Our game team is working on a new original IP called, Uncharted: Drake's Fortune that debuted at E3 of 2006. I have provided the game trailer, along with some press about the game. Demo: www.naughtydog.com/comingsoon/index.html Press from: Uncharted: Drake's Fortune . "Naughty Dog's new franchise for the PS3 could be the biggest first-party title of the year." -Gamespy . "Naughty Dog has always had a reputation for squeezing the utmost performance and fidelity out of Sony's hardware, and it looks like that tradition will continue with Uncharted." -Gamespot (Gamespot Preview) In addition to our game team, Naughty Dog is home to the ICE Team, one of Sony's World Wide Studios central technology groups. The ICE Team focuses on creating core graphics technologies for Sony's worldwide first party published titles for the PLAYSTATIONR3, including low level game engine components, graphics processing pipelines, supporting tools, and GUI profiling and debugging tools. More recently the ICE Team's scope has expanded in order to build engine components and tools for use by third party developers. The first two of these are PLAYSTATIONREdge, a set of components that enables developers to get better performance out of the PLAYSTATIONR3, and GCM Replay, which provides analysis, debugging, and profiling for the RSXT. Please feel free to contact me directly if this is something that you or someone you know may be interested in hearing more about. Candace Walker Recruiter http://www.linkedin.com/in/candacerwalker Naughty Dog, Inc. 1601 Cloverfield Blvd. Suite 6000 North Santa Monica, CA 90404 candace_walker at naughtydog.com Phone: 310-633-9275 www.naughtydog.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave at boost-consulting.com Mon Oct 15 21:43:54 2007 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 15 Oct 2007 09:43:54 -1000 Subject: [C++-sig] Header error in boost/python/object/make_holder? References: Message-ID: <87bqb0p3id.fsf@grogan.peloton> on Wed Oct 10 2007, "Michel Valstar" wrote: > I am trying to build code of a recently graduated student, who is now unavailable to us (read: > ignores us). When running scons in the appropriate directory, a lot gets build, until I get the > following error: > > /usr/include/boost/python/object/make_holder.hpp:81: error: 'allocate' is not a member of > 'boost::python::objects::value_holder , std::allocator >, State> >' > /usr/include/boost/python/object/make_holder.hpp:83: error: no matching function for call to > 'boost::python::objects::value_holder , std::allocator >, State> >::value_holder(int*&)' > /usr/include/boost/python/object/value_holder.hpp:44: note: candidates are: > boost::python::objects::value_holder , std::allocator >, State> >::value_holder() > /usr/include/boost/python/object/value_holder.hpp:44: note: > boost::python::objects::value_holder , std::allocator >, State> >::value_holder(const > boost::python::objects::value_holder , std::allocator >, State> >&) > scons: *** [trackerbase/trackerbasewrapper.os] Error 1 > scons: building terminated because of errors. > > This does not seem to be an error in his own code, rather an error in the boost.python code? > This is the first time I am using boost, and, as usual, I need to get this program working > yesterday. > > My machine is a recently installed Ubuntu Feisty (hence the need for re-compilation). I am using > the latest version of Boost (boost_1_34_1) and python 2.5.1 > > Any help would be appreciated. I'll try. First, please read the Note at http://boost.org/libs/python/doc/building.html#no-install-quickstart Also, please note that http://boost.org/more/mailing_lists.htm#cplussig may be a better place to ask this question. I'm following up there. I'm pretty sure this is an error in your student's code and the compiler is giving you a poor error message. Most probably std::pair,std::allocator >, State> is an incomplete type at the point where make_holder is being used. However, guessing is really futile. If my guess is wrong, please prepare and post a minimal, complete example as described in http://article.gmane.org/gmane.comp.python.c++/10237/match=minimal+complete+example+reproduce+jamfile 9 times out of 10, preparing a minimal example reveals the actual problem to the person asking the question ;-) Cheers, -- Dave Abrahams Boost Consulting http://www.boost-consulting.com From thauk at novuscom.net Mon Oct 15 23:47:31 2007 From: thauk at novuscom.net (Thomas Hauk) Date: Mon, 15 Oct 2007 14:47:31 -0700 Subject: [C++-sig] Header error in boost/python/object/make_holder? In-Reply-To: <87bqb0p3id.fsf@grogan.peloton> References: <87bqb0p3id.fsf@grogan.peloton> Message-ID: <39935981-EB2A-48B6-BCFD-9E761923A477@novuscom.net> On Oct 15, 2007, at 12:43 PM, David Abrahams wrote: > 9 times out of 10, preparing a minimal example reveals the actual > problem to the person asking the question ;-) Speaking of which, and I'm changing the subject rather selfishly, but I still haven't had an answer about what the bindings to: struct Foo { unsigned char data[4]; }; should be... and I don't think that type of question to this newsgroup gets any more minimal than that. :) T -- Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. --Jamie Zawinski, in comp.lang.emacs From Chang_Chen at sonic.com Tue Oct 16 11:23:13 2007 From: Chang_Chen at sonic.com (Chang Chen) Date: Tue, 16 Oct 2007 17:23:13 +0800 Subject: [C++-sig] a question about boost python Message-ID: <51C471E6CBEC8148A08E065690F4DBDF01679716@SHAEXC01.ent.sonic.com> Hi All I have a set of functions which last parameters are out-parameter. i.e. void function1(int t1, float t2, string& t3) ; I want to expose these functions in python, but such definition (~def("function1", function1)~) is not what I want. Because we have to write python code like this: strTest='' function1(1,2.0,strTest); I prefer to writing python code like this strTest = funciton1(1,2.0) Is there any idea to solve this question? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Tue Oct 16 12:21:31 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 16 Oct 2007 12:21:31 +0200 Subject: [C++-sig] access struct inside class In-Reply-To: <47122DE1.3050801@dackbrann.net> References: <47122DE1.3050801@dackbrann.net> Message-ID: <7465b6170710160321h406f2605sf55a122f0b021db1@mail.gmail.com> On 10/14/07, Simon Norberg wrote: > > Hello, > im trying to get python to read and write to a struct inside a class > in the same way i do in c++ > Customers hej; > hej.address.contact = "The Devil"; > > but i cant even get the code to compile, any suggestions? > > #include > #include > > using namespace std; > class Customers { > private: > struct s_address > { > string contact; > string street1; > string street2; > string city; > string province; > string postalCode; > string country; > }; > public: > s_address address; > Customers(){} > ~Customers(){} > }; > 1. you cannot export variable, without exporting its type first: you have to expose s_address class too, if you want to expose address mem. variable. 2. here is the code that was generated by Py++( http://language-binding.net/), the only change I did for original code was to change everything to public. #include "boost/python.hpp" #include "1.hpp" namespace bp = boost::python; BOOST_PYTHON_MODULE(pyplusplus){ { //::Customers typedef bp::class_< Customers > Customers_exposer_t; Customers_exposer_t Customers_exposer = Customers_exposer_t( "Customers" ); bp::scope Customers_scope( Customers_exposer ); bp::class_< Customers::s_address >( "s_address" ) .def_readwrite( "city", &Customers::s_address::city ) .def_readwrite( "contact", &Customers::s_address::contact ) .def_readwrite( "country", &Customers::s_address::country ) .def_readwrite( "postalCode", &Customers::s_address::postalCode ) .def_readwrite( "province", &Customers::s_address::province ) .def_readwrite( "street1", &Customers::s_address::street1 ) .def_readwrite( "street2", &Customers::s_address::street2 ); Customers_exposer.def( bp::init< >() ); Customers_exposer.def_readonly( "address", &Customers::address ); } } -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Tue Oct 16 12:23:55 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 16 Oct 2007 12:23:55 +0200 Subject: [C++-sig] a question about boost python In-Reply-To: <51C471E6CBEC8148A08E065690F4DBDF01679716@SHAEXC01.ent.sonic.com> References: <51C471E6CBEC8148A08E065690F4DBDF01679716@SHAEXC01.ent.sonic.com> Message-ID: <7465b6170710160323t6e4025d1u827042e325f31be6@mail.gmail.com> On 10/16/07, Chang Chen wrote: > > Hi All > > I have a set of functions which last parameters are out-parameter. i.e. > > void function1(int t1, float t2, string& t3) ; > > I want to expose these functions in python, but such definition (~def(" > function1", function1)~) is not what I want. > > Because we have to write python code like this: > > strTest='' > > function1(1,2.0,strTest); > > I prefer to writing python code like this > > strTest = funciton1(1,2.0) > > Is there any idea to solve this question? > In short: to create another function, with the desired interface. In your case you just don't have other choice - std::string is mapped to Python string, which is immutable. Read more here: http://language-binding.net/pyplusplus/documentation/functions/transformation/built_in/output.html -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Tue Oct 16 12:31:39 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 16 Oct 2007 12:31:39 +0200 Subject: [C++-sig] Header error in boost/python/object/make_holder? In-Reply-To: <39935981-EB2A-48B6-BCFD-9E761923A477@novuscom.net> References: <87bqb0p3id.fsf@grogan.peloton> <39935981-EB2A-48B6-BCFD-9E761923A477@novuscom.net> Message-ID: <7465b6170710160331n7e00fc91q3725cbc52124541f@mail.gmail.com> On 10/15/07, Thomas Hauk wrote: > > On Oct 15, 2007, at 12:43 PM, David Abrahams wrote: > > 9 times out of 10, preparing a minimal example reveals the actual > > problem to the person asking the question ;-) > > Speaking of which, and I'm changing the subject rather selfishly, but > I still haven't had an answer about what the bindings to: > > struct Foo > { > unsigned char data[4]; > }; > > should be... and I don't think that type of question to this > newsgroup gets any more minimal than that. :) > Next code was generated by Py++, may be it is not optimal but it does the work. __array_1.pypp.hpp file is attached #include "boost/python.hpp" #include "__array_1.pypp.hpp" #include "1.hpp" namespace bp = boost::python; struct Foo_wrapper : Foo, bp::wrapper< Foo > { Foo_wrapper(Foo const & arg ) : Foo( arg ) , bp::wrapper< Foo >(){ // copy constructor } Foo_wrapper() : Foo() , bp::wrapper< Foo >(){ // null constructor } static pyplusplus::containers::static_sized::array_1_t< unsigned char, 4> pyplusplus_data_wrapper( ::Foo & inst ){ return pyplusplus::containers::static_sized::array_1_t< unsigned char, 4>( inst.data ); } }; BOOST_PYTHON_MODULE(pyplusplus){ { //::Foo typedef bp::class_< Foo_wrapper > Foo_exposer_t; Foo_exposer_t Foo_exposer = Foo_exposer_t( "Foo" ); bp::scope Foo_scope( Foo_exposer ); pyplusplus::containers::static_sized::register_array_1< unsigned char, 4 >( "__array_1_unsigned_char_4" ); { //Foo::data [variable], type=unsigned char[4] typedef pyplusplus::containers::static_sized::array_1_t< unsigned char, 4> ( *array_wrapper_creator )( ::Foo & ); Foo_exposer.add_property( "data" , bp::make_function( array_wrapper_creator(&Foo_wrapper::pyplusplus_data_wrapper) , bp::with_custodian_and_ward_postcall< 0, 1 >() ) ); } } } -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: __array_1.pypp.hpp Type: text/x-c++hdr Size: 5152 bytes Desc: not available URL: From patrick.hartling at gmail.com Tue Oct 16 17:00:58 2007 From: patrick.hartling at gmail.com (Patrick Hartling) Date: Tue, 16 Oct 2007 10:00:58 -0500 Subject: [C++-sig] Problems passing objects to function by const reference Message-ID: <944f7d8e0710160800l631fc01dk936d0af20472f91f@mail.gmail.com> In our uses of Boost.Python, we have run into a case where very simple code fails to compile. The case that we have is that a class type has no public destructor and instantiations of that type are passed by const reference into a function. The Boost.Python code for exposing the function that accepts the objects fail to compile because an attempt is made to call the non-public destructor. The attached code demonstrates what we are trying to do. The compile error from GCC 4.1 when compiling against Boost 1.34.1 is as follows: destroy_test.h: In static member function 'static void boost::python::detail::value_destroyer::execute(const volatile T*) [with T = C]': .../boost-1.34.1/include/boost-1_34_1/boost/python/detail/destroy.hpp:90: instantiated from 'void boost::python::detail::destroy_referent_impl(void*, T& (*)()) [with T = const C]' .../boost-1.34.1/include/boost-1_34_1/boost/python/detail/destroy.hpp:101: instantiated from 'void boost::python::detail::destroy_referent(void*, T (*)()) [with T = const C&]' .../boost-1.34.1/include/boost-1_34_1/boost/python/converter/rvalue_from_python_data.hpp:135: instantiated from 'boost::python::converter::rvalue_from_python_data::~rvalue_from_python_data() [with T = const C&]' .../boost-1.34.1/include/boost-1_34_1/boost/python/converter/arg_from_python.hpp:108: instantiated from 'PyObject* boost::python::detail::caller_arity<1u>::impl::operator()(PyObject*, PyObject*) [with F = void (*)(const C&), Policies = boost::python::default_call_policies, Sig = boost::mpl::vector2]' .../boost-1.34.1/include/boost-1_34_1/boost/python/object/py_function.hpp:38: instantiated from 'PyObject* boost::python::objects::caller_py_function_impl::operator()(PyObject*, PyObject*) [with Caller = boost::python::detail::caller >]' generated.cpp:21: instantiated from here destroy_test.h:4: error: 'C::~C()' is protected .../boost-1.34.1/include/boost-1_34_1/boost/python/detail/destroy.hpp:33: error: within this context I have tried to understand what Boost.Python is doing internally, and it seems like a copy of the object is being made that is later cleaned up by calling the destructor explicitly. I could definitely be wrong about that assessment, though. Ultimately, what I don't understand is why anything needs to be destroyed in this case. -Patirck -- Patrick L. Hartling http://www.137.org/patrick/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: destroy_test.h URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: generated.cpp URL: From grh at mur.at Tue Oct 16 17:45:49 2007 From: grh at mur.at (Georg Holzmann) Date: Tue, 16 Oct 2007 17:45:49 +0200 Subject: [C++-sig] datastructure to numpy and back In-Reply-To: <4713AC69.4000804@mur.at> References: <4713AC69.4000804@mur.at> Message-ID: <4714DCAD.6050300@mur.at> Hallo again ! I still did not get it working with boost (after quite some reading and searching) ... aren't there any examples out there how to do that ? Or maybe is it better to use SWIG or directly the NumPy C-API for that ? Thanks, LG Georg Georg Holzmann schrieb: > Hallo! > > I know this was discussed quite some times, but I did find that many > workarounds and not really a common way how to do that with Boost.Python > ... so I am a little bit confused ... > > My problem: I have a class with some (big) custom C++ matrix types and I > want to write some getters/setters for them to/from numpy arrays, where > I want to avoid copies of the data. > > So is there a common way to do this ? > (e.g. num_util from > http://www.eos.ubc.ca/research/clouds/software/pythonlibs/num_util/num_util_release2/Readme.html > ?) > > Or can maybe someone link me to some docu or examples which already did > this ? (it must be quite common ...) > > Many thanks for any hint, > LG > Georg > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig From matthieu.brucher at gmail.com Tue Oct 16 17:55:00 2007 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 16 Oct 2007 17:55:00 +0200 Subject: [C++-sig] datastructure to numpy and back In-Reply-To: <4714DCAD.6050300@mur.at> References: <4713AC69.4000804@mur.at> <4714DCAD.6050300@mur.at> Message-ID: Hi, I've written a swig wrapper around a structure that could be used for wrapping anything that needs to expose the __array_struct__ property (didn't had the time to try Boost with Albert's wrappers). It is not available on the net, but it is based on some mails that were sent here and on the Pyrex example for the array interface. Matthieu 2007/10/16, Georg Holzmann : > > Hallo again ! > > I still did not get it working with boost (after quite some reading and > searching) ... aren't there any examples out there how to do that ? > > Or maybe is it better to use SWIG or directly the NumPy C-API for that ? > > Thanks, > LG > Georg > > Georg Holzmann schrieb: > > Hallo! > > > > I know this was discussed quite some times, but I did find that many > > workarounds and not really a common way how to do that with Boost.Python > > ... so I am a little bit confused ... > > > > My problem: I have a class with some (big) custom C++ matrix types and I > > want to write some getters/setters for them to/from numpy arrays, where > > I want to avoid copies of the data. > > > > So is there a common way to do this ? > > (e.g. num_util from > > > http://www.eos.ubc.ca/research/clouds/software/pythonlibs/num_util/num_util_release2/Readme.html > > ?) > > > > Or can maybe someone link me to some docu or examples which already did > > this ? (it must be quite common ...) > > > > Many thanks for any hint, > > LG > > Georg > > _______________________________________________ > > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From thauk at novuscom.net Tue Oct 16 17:55:16 2007 From: thauk at novuscom.net (Thomas Hauk) Date: Tue, 16 Oct 2007 08:55:16 -0700 Subject: [C++-sig] Header error in boost/python/object/make_holder? In-Reply-To: <7465b6170710160331n7e00fc91q3725cbc52124541f@mail.gmail.com> References: <87bqb0p3id.fsf@grogan.peloton> <39935981-EB2A-48B6-BCFD-9E761923A477@novuscom.net> <7465b6170710160331n7e00fc91q3725cbc52124541f@mail.gmail.com> Message-ID: <5C34DA80-A480-4B0C-B801-5DC0853E350A@novuscom.net> On Oct 16, 2007, at 3:31 AM, Roman Yakovenko wrote: > Next code was generated by Py++, may be it is not optimal but it > does the work. __array_1.pypp.hpp file is attached Thanks for the code, Roman. I must say how surprised I am at the amount of code it takes to wrap a struct containing only an array of chars! Is this a limitation of the way C++ and Python get bound, or is this because of some inefficiency in Boost.Python? If the latter, I would hope that this becomes a new base case for improving the package. Would it be easier to wrap this using another technology, like SWIG? T -- Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. --Jamie Zawinski, in comp.lang.emacs From roman.yakovenko at gmail.com Tue Oct 16 18:05:28 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 16 Oct 2007 18:05:28 +0200 Subject: [C++-sig] Header error in boost/python/object/make_holder? In-Reply-To: <5C34DA80-A480-4B0C-B801-5DC0853E350A@novuscom.net> References: <87bqb0p3id.fsf@grogan.peloton> <39935981-EB2A-48B6-BCFD-9E761923A477@novuscom.net> <7465b6170710160331n7e00fc91q3725cbc52124541f@mail.gmail.com> <5C34DA80-A480-4B0C-B801-5DC0853E350A@novuscom.net> Message-ID: <7465b6170710160905h411712b4l722645a4e496b3e6@mail.gmail.com> On 10/16/07, Thomas Hauk wrote: > > On Oct 16, 2007, at 3:31 AM, Roman Yakovenko wrote: > > Next code was generated by Py++, may be it is not optimal but it > > does the work. __array_1.pypp.hpp file is attached > > Thanks for the code, Roman. > > I must say how surprised I am at the amount of code it takes to wrap > a struct containing only an array of chars! Is this a limitation of > the way C++ and Python get bound, I warned you about code size. First of all this is how Py++ generates the code in this case. Second if you will use indexing suite V2, than the amount of code will drop. or is this because of some > inefficiency in Boost.Python? I didn't tested the code for efficiency, but it doesn't copy the array, just provides access to the items. So I don't expect problems with it. If the latter, I would hope that this > becomes a new base case for improving the package. > > Would it be easier to wrap this using another technology, like SWIG? > Don't know never used it. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthew.scouten at gmail.com Tue Oct 16 19:31:40 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Tue, 16 Oct 2007 12:31:40 -0500 Subject: [C++-sig] passing a vector of structs Message-ID: <3dc9bcf00710161031w5d0c8213qf41095ae1f0f2551@mail.gmail.com> I have a vector of 'struct foo' in c++ that needs to be passed to a function python. 'struct foo' is an extremely simple structure containing 3 ints and a trivial ctor. so I create a foo_wrapper: struct foo_wrapper : foo , wrapper { foo_wrapper(const foo& f); foo_wrapper(); }; and export it: class_("foo") .def(init<>()) .def_readwrite("iE", &foo::iE ) .def_readwrite("bA", &foo::bA) .def_readwrite("bL", &foo::bL) ; next I export a vector of foo_wrappers: class_< std::vector >("VectorOfFoo") .def(vector_indexing_suite< std::vector, true >() ); I pass the vector to a python function: Traceback (most recent call last): File "C:\redacted", line 23, in pc.RequestExchangeList() TypeError: No to_python (by-value) converter found for C++ type: class std::vector > I try to copy the elements to a new vector, it seems to work fine, untill I try to access an element of that vector and get: Traceback (most recent call last): File "", line 1, in File "", line 7, in OnExchangeList TypeError: No to_python (by-value) converter found for C++ type: struct TTExchangeStruct_wrapper So what am I doing wrong? How am I supposed to pass a vector of structs from c++ to python? From roman.yakovenko at gmail.com Tue Oct 16 20:48:45 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 16 Oct 2007 20:48:45 +0200 Subject: [C++-sig] passing a vector of structs In-Reply-To: <3dc9bcf00710161031w5d0c8213qf41095ae1f0f2551@mail.gmail.com> References: <3dc9bcf00710161031w5d0c8213qf41095ae1f0f2551@mail.gmail.com> Message-ID: <7465b6170710161148w6823d529k7bffad2a9b4693ce@mail.gmail.com> On 10/16/07, Matthew Scouten wrote: > > I have a vector of 'struct foo' in c++ that needs to be passed to a > function python. > > 'struct foo' is an extremely simple structure containing 3 ints and a > trivial ctor. > > so I create a foo_wrapper: > > struct foo_wrapper : foo , wrapper > { > foo_wrapper(const foo& f); > foo_wrapper(); > }; In this case you don't need to create wrapper and export it: > > class_("foo") > .def(init<>()) > .def_readwrite("iE", &foo::iE ) > .def_readwrite("bA", &foo::bA) > .def_readwrite("bL", &foo::bL) > ; > > next I export a vector of foo_wrappers: > > class_< std::vector >("VectorOfFoo") > .def(vector_indexing_suite< std::vector, true > >() ); > > I pass the vector to a python function: > > Traceback (most recent call last): > File "C:\redacted", line 23, in > pc.RequestExchangeList() > TypeError: No to_python (by-value) converter found for C++ type: class > std::vector > > > I try to copy the elements to a new vector, it seems to > work fine, untill I try to access an element of that vector and get: > > Traceback (most recent call last): > File "", line 1, in > File "", line 7, in OnExchangeList > TypeError: No to_python (by-value) converter found for C++ type: > struct TTExchangeStruct_wrapper > > So what am I doing wrong? How am I supposed to pass a vector of > structs from c++ to python? You need to post small and complete example. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From hans_meine at gmx.net Tue Oct 16 22:37:04 2007 From: hans_meine at gmx.net (Hans Meine) Date: Tue, 16 Oct 2007 22:37:04 +0200 Subject: [C++-sig] How about class_<...>.enable_copy() ? In-Reply-To: <200707232257.05883.meine@informatik.uni-hamburg.de> References: <200706081706.37240.meine@informatik.uni-hamburg.de> <200707231922.15574.meine@informatik.uni-hamburg.de> <200707232257.05883.meine@informatik.uni-hamburg.de> Message-ID: <200710162237.08845.hans_meine@gmx.net> Hi again! Anyone cares to comment on my older posting? On Montag 23 Juli 2007, Hans Meine wrote: > On Montag 23 Juli 2007, Hans Meine wrote: > > foo = Foo(other) # copy constructor as in C++ (1) > > foo = copy.copy(other) # pythonic copying (2) > > foo = copy.deepcopy(other) # deepcopying (3) > > > > (1) is easy to do by exporting the copy constructor > > > > (2) could be implemented by setting __copy__ to the above copy > > constructor, but one would assume __dict__ to be (non-deep)copied, too. > > > > (3) definitely needs its own implementation, which needs to call deepcopy > > recursively. > > > > I would still believe that an .enable_copy() would be very handy. It > > could possibly be controlled by an enum arg which of the above methods > > should be exported. Here is the updated, perfectly working code for (2) and (3), which I propose to be included in BPL. Also, some things appear hackish to me -- I would be glad to get feedback on how to do this in a more "standard" way: a) wrap a pointer to a newly created object in a bp::object -- there must be a shorter/better way than bp::detail::new_reference(typename manage_new_object::apply::type()(p) no? b) shouldn't a 64bit-safe version of inline id(object) { return (int)(copyable.ptr()); } be added to boost::python? c) is my solution of accessing copy/deepcopy improvable? (I guess not - it looks already quite OK to me.) d) would you use the visitor pattern, i.e. class_::enable_copy for the above code? AFAICS, there are two small advantages: * both functions can be def'd in one line * the type does not have to be repeated, but is fetched from the class_<> template instance > Maybe someone is interested in turning my code into a standard BPL > facility? (BTW: Is __dict__ created on demand? Then one should probably > add a guard to both my __copy__ and __deepcopy__.) I'd like to get an authoritive answer on this - do BPL-exported objects always have a __dict__, or is it only created on demand/access? > On Montag 23 Juli 2007, Hans Meine wrote: > > Probably I should use PyImport_ImportModule or the new > > boost::python::import. > > Speaking of the latter, shouldn't the python:: prefix be removed from the > code within boost_1_34_0/libs/python/src/import.cpp ? I recently had > syntax errors from GCC-4.1.2 within kdelibs-3.5.7 with a similar case: > > namespace KABC { > > > > class KABC_EXPORT Field > > { > > public: > > virtual QString value( const KABC::Addressee & ); > > Here, I had to remove KABC:: in order to let it compile. (Which I found > surprising, but anyways.) This is not very much related, but interesting. -- Ciao, / / .o. /--/ ..o / / ANS ooo -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From Chang_Chen at sonic.com Wed Oct 17 05:38:23 2007 From: Chang_Chen at sonic.com (Chang Chen) Date: Wed, 17 Oct 2007 11:38:23 +0800 Subject: [C++-sig] a question about boost python Message-ID: <51C471E6CBEC8148A08E065690F4DBDF01679895@SHAEXC01.ent.sonic.com> I know we need define a wrapper, but our function signature is quite regular. i.e. only the last parameter is output parameter, so I want to write a template, so that such wrapper can be easily written. Our function definition looks like: void function1(int t1, float t2, string& t3) ; I want to define a template: template struct FunctionConvert< Return (*) ( T1 , T2, TOUT& ) > { typedef functionT Return (*) ( T1 , T2, TOUT& ); static TOUT run(functionT P,const T1& t1, const T2& t2) { TOUT out; P(t1,t2,out); return out; } } But I do not know how to integrate it with boost python :(. - Chang From meine at informatik.uni-hamburg.de Wed Oct 17 10:25:02 2007 From: meine at informatik.uni-hamburg.de (Hans Meine) Date: Wed, 17 Oct 2007 10:25:02 +0200 Subject: [C++-sig] How about class_<...>.enable_copy() ? In-Reply-To: <200710162237.08845.hans_meine@gmx.net> References: <200706081706.37240.meine@informatik.uni-hamburg.de> <200707232257.05883.meine@informatik.uni-hamburg.de> <200710162237.08845.hans_meine@gmx.net> Message-ID: <200710171025.02589.meine@informatik.uni-hamburg.de> Am Dienstag, 16. Oktober 2007 22:37:04 schrieb Hans Meine: > Here is the updated, perfectly working code for (2) and (3), which I > propose to be included in BPL. Also, some things appear hackish to me -- I > would be glad to get feedback on how to do this in a more "standard" way: Ooops - of course I indented to attach something.. -- Ciao, / / /--/ / / ANS -------------- next part -------------- A non-text attachment was scrubbed... Name: foo_copying.cxx Type: text/x-c++src Size: 1227 bytes Desc: not available URL: From Chang_Chen at sonic.com Wed Oct 17 10:30:01 2007 From: Chang_Chen at sonic.com (Chang Chen) Date: Wed, 17 Oct 2007 16:30:01 +0800 Subject: [C++-sig] How about class_<...>.enable_copy() ? In-Reply-To: <200710171025.02589.meine@informatik.uni-hamburg.de> Message-ID: <51C471E6CBEC8148A08E065690F4DBDF016799A7@SHAEXC01.ent.sonic.com> Test reply Nothing... -----Original Message----- From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Hans Meine Sent: Wednesday, October 17, 2007 4:25 PM To: Development of Python/C++ integration Subject: Re: [C++-sig] How about class_<...>.enable_copy() ? Am Dienstag, 16. Oktober 2007 22:37:04 schrieb Hans Meine: > Here is the updated, perfectly working code for (2) and (3), which I > propose to be included in BPL. Also, some things appear hackish to me -- I > would be glad to get feedback on how to do this in a more "standard" way: Ooops - of course I indented to attach something.. -- Ciao, / / /--/ / / ANS From matthew.scouten at gmail.com Wed Oct 17 16:31:26 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Wed, 17 Oct 2007 09:31:26 -0500 Subject: [C++-sig] passing a vector of structs In-Reply-To: <7465b6170710161148w6823d529k7bffad2a9b4693ce@mail.gmail.com> References: <3dc9bcf00710161031w5d0c8213qf41095ae1f0f2551@mail.gmail.com> <7465b6170710161148w6823d529k7bffad2a9b4693ce@mail.gmail.com> Message-ID: <3dc9bcf00710170731l4d0e578dw6ac9b4b79ca891aa@mail.gmail.com> On 10/16/07, Roman Yakovenko wrote: > On 10/16/07, Matthew Scouten wrote: > > I have a vector of 'struct foo' in c++ that needs to be passed to a > > function python. > > > > 'struct foo' is an extremely simple structure containing 3 ints and a > > trivial ctor. > > > > so I create a foo_wrapper: > > > > struct foo_wrapper : foo , wrapper > > { > > foo_wrapper(const foo& f); > > foo_wrapper(); > > }; > > In this case you don't need to create wrapper > > > and export it: > > > > class_("foo") > > .def(init<>()) > > .def_readwrite("iE", &foo::iE ) > > .def_readwrite("bA", &foo::bA) > > .def_readwrite("bL", &foo::bL) > > ; > > > > next I export a vector of foo_wrappers: > > > > class_< std::vector >("VectorOfFoo") > > .def(vector_indexing_suite< > std::vector, true >() ); > > > > I pass the vector to a python function: > > > > Traceback (most recent call last): > > File "C:\redacted", line 23, in > > pc.RequestExchangeList() > > TypeError: No to_python (by-value) converter found for C++ type: class > > std::vector > > > > > I try to copy the elements to a new vector, it seems to > > work fine, untill I try to access an element of that vector and get: > > > > Traceback (most recent call last): > > File "", line 1, in > > File "", line 7, in OnExchangeList > > TypeError: No to_python (by-value) converter found for C++ type: > > struct TTExchangeStruct_wrapper > > > > So what am I doing wrong? How am I supposed to pass a vector of > > structs from c++ to python? > > > You need to post small and complete example. > > -- > Roman Yakovenko Right, OK: TTExchangeStruct_wrapper is my foo_wrapper. I forgot to change that when sanitizing and simplifying me example. I split out the problem code and made a stand alone compilable example: c++ & boost::python: struct foo { foo():one(1),two(2),three(3) {} int one; int two; int three; }; //The std::vector Indexing Suite seems to want this //I Don't know why. bool operator==(foo lhs ,foo rhs) { return &lhs == &rhs; } struct foo_wrapper : foo , wrapper { foo_wrapper(const foo& f); foo_wrapper(); }; foo_wrapper::foo_wrapper(const foo& exch): foo(exch), wrapper(){} foo_wrapper::foo_wrapper(): foo(), wrapper(){} class busyBox { public: int callout(); virtual void callback(std::vector vf) {}; }; int busyBox::callout() { std::vector vf(10); callback(vf); return 0; } class busyBox_wrapper: public busyBox, public wrapper { public: busyBox_wrapper(); busyBox_wrapper(const busyBox &); int callout(); virtual void callback(std::vector vf); void default_callback(std::vector vf); }; busyBox_wrapper::busyBox_wrapper() : busyBox(), wrapper(){} busyBox_wrapper::busyBox_wrapper(const busyBox &bb ) : busyBox(bb), wrapper(){} int busyBox_wrapper::callout() { return busyBox::callout(); } void busyBox_wrapper::callback (std::vector vf) { if (override callbackPy = this->get_override("callback")) { std::vector vfw; for (unsigned int i = 0; i < vf.size(); ++i) vfw.push_back(vf[i]); //callbackPy(vf); callbackPy(vfw); return; } return busyBox::callback(vf); } void busyBox_wrapper::default_callback(std::vector vf) { return busyBox::callback(vf); } BOOST_PYTHON_MODULE(BusyBox) { class_("busyBox") .def("callback",&busyBox_wrapper::default_callback) .def("callout", &busyBox_wrapper::callout); class_("foo") .def(init<>()) .def_readwrite("one", &foo::one ) .def_readwrite("two", &foo::two) .def_readwrite("three", &foo::three) ; class_< std::vector >("std::vectorOfFoo") .def(vector_indexing_suite< std::vector, true>()); } and here is the python code to invoke the error: import BusyBox class subBusybox(BusyBox.busyBox): def callback(self, vf): print [x for x in vf] sbb = subBusybox() sbb.callout() and here it the error itself(it fails while invoking the 'print [x for x in vf]' line ): Traceback (most recent call last): File "", line 1, in File "", line 3, in callback TypeError: No to_python (by-value) converter found for C++ type: struct foo_wrapper To reiterate my question: I need to pass a vector of structs from a c++ function to a python function. What am I doing wrong? From matthew.scouten at gmail.com Wed Oct 17 22:53:31 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Wed, 17 Oct 2007 15:53:31 -0500 Subject: [C++-sig] passing a vector of structs In-Reply-To: <3dc9bcf00710170731l4d0e578dw6ac9b4b79ca891aa@mail.gmail.com> References: <3dc9bcf00710161031w5d0c8213qf41095ae1f0f2551@mail.gmail.com> <7465b6170710161148w6823d529k7bffad2a9b4693ce@mail.gmail.com> <3dc9bcf00710170731l4d0e578dw6ac9b4b79ca891aa@mail.gmail.com> Message-ID: <3dc9bcf00710171353mbdfd3b7lcc04f93e3cf493bf@mail.gmail.com> On 10/17/07, Matthew Scouten wrote: > On 10/16/07, Roman Yakovenko wrote: > > On 10/16/07, Matthew Scouten wrote: > > > I have a vector of 'struct foo' in c++ that needs to be passed to a > > > function python. > > > > > > 'struct foo' is an extremely simple structure containing 3 ints and a > > > trivial ctor. > > > > > > so I create a foo_wrapper: > > > > > > struct foo_wrapper : foo , wrapper > > > { > > > foo_wrapper(const foo& f); > > > foo_wrapper(); > > > }; > > > > In this case you don't need to create wrapper > > > > > and export it: > > > > > > class_("foo") > > > .def(init<>()) > > > .def_readwrite("iE", &foo::iE ) > > > .def_readwrite("bA", &foo::bA) > > > .def_readwrite("bL", &foo::bL) > > > ; > > > > > > next I export a vector of foo_wrappers: > > > > > > class_< std::vector >("VectorOfFoo") > > > .def(vector_indexing_suite< > > std::vector, true >() ); > > > > > > I pass the vector to a python function: > > > > > > Traceback (most recent call last): > > > File "C:\redacted", line 23, in > > > pc.RequestExchangeList() > > > TypeError: No to_python (by-value) converter found for C++ type: class > > > std::vector > > > > > > > I try to copy the elements to a new vector, it seems to > > > work fine, untill I try to access an element of that vector and get: > > > > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "", line 7, in OnExchangeList > > > TypeError: No to_python (by-value) converter found for C++ type: > > > struct TTExchangeStruct_wrapper > > > > > > So what am I doing wrong? How am I supposed to pass a vector of > > > structs from c++ to python? > > > > > > You need to post small and complete example. > > > > -- > > Roman Yakovenko > > Right, OK: > TTExchangeStruct_wrapper is my foo_wrapper. I forgot to change that > when sanitizing and simplifying me example. I split out the problem > code and made a stand alone compilable example: > > c++ & boost::python: > > struct foo > { > foo():one(1),two(2),three(3) {} > > int one; > int two; > int three; > }; > > //The std::vector Indexing Suite seems to want this > //I Don't know why. > bool operator==(foo lhs ,foo rhs) > { > return &lhs == &rhs; > } > > struct foo_wrapper : foo , wrapper > { > foo_wrapper(const foo& f); > foo_wrapper(); > }; > > foo_wrapper::foo_wrapper(const foo& exch): foo(exch), wrapper(){} > > foo_wrapper::foo_wrapper(): foo(), wrapper(){} > > class busyBox > { > public: > int callout(); > virtual void callback(std::vector vf) {}; > }; > > int busyBox::callout() > { > std::vector vf(10); > callback(vf); > return 0; > } > > class busyBox_wrapper: public busyBox, public wrapper > { > public: > busyBox_wrapper(); > busyBox_wrapper(const busyBox &); > int callout(); > virtual void callback(std::vector vf); > void default_callback(std::vector vf); > }; > > busyBox_wrapper::busyBox_wrapper() : busyBox(), wrapper(){} > > busyBox_wrapper::busyBox_wrapper(const busyBox &bb ) : busyBox(bb), > wrapper(){} > > int busyBox_wrapper::callout() > { > return busyBox::callout(); > } > > void busyBox_wrapper::callback (std::vector vf) > { > if (override callbackPy = this->get_override("callback")) > { > > std::vector vfw; > for (unsigned int i = 0; i < vf.size(); ++i) > vfw.push_back(vf[i]); > > //callbackPy(vf); > callbackPy(vfw); > > return; > } > return busyBox::callback(vf); > } > > void busyBox_wrapper::default_callback(std::vector vf) > { > return busyBox::callback(vf); > } > > > > BOOST_PYTHON_MODULE(BusyBox) > { > > class_("busyBox") > .def("callback",&busyBox_wrapper::default_callback) > .def("callout", &busyBox_wrapper::callout); > > class_("foo") > .def(init<>()) > .def_readwrite("one", &foo::one ) > .def_readwrite("two", &foo::two) > .def_readwrite("three", &foo::three) > ; > > class_< std::vector >("std::vectorOfFoo") > .def(vector_indexing_suite< std::vector, true>()); > } > > and here is the python code to invoke the error: > > import BusyBox > > class subBusybox(BusyBox.busyBox): > def callback(self, vf): > print [x for x in vf] > > > sbb = subBusybox() > sbb.callout() > > and here it the error itself(it fails while invoking the 'print [x for > x in vf]' line ): > > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in callback > TypeError: No to_python (by-value) converter found for C++ type: > struct foo_wrapper > > > > To reiterate my question: I need to pass a vector of structs from a > c++ function to a python function. What am I doing wrong? > UPDATE: Well, with no reply from the list, I spent all day trying to find my error. It turns out that I was temporarily stupid. If the above lines are changed from: class_< std::vector >("std::vectorOfFoo") .def(vector_indexing_suite< std::vector, true>()); to: class_< std::vector >("std::vectorOfFoo") .def(vector_indexing_suite< std::vector, true>()); it fixes everything. From matthew.scouten at gmail.com Thu Oct 18 23:52:54 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Thu, 18 Oct 2007 16:52:54 -0500 Subject: [C++-sig] I can't get None Message-ID: <3dc9bcf00710181452g252a364cw637141b093570b1@mail.gmail.com> I want to return None from a c++ function. I have googled for how to do this with no good results. How do I get an object with None in c++? From nat at lindenlab.com Fri Oct 19 00:01:30 2007 From: nat at lindenlab.com (Nat Goodspeed) Date: Thu, 18 Oct 2007 18:01:30 -0400 Subject: [C++-sig] I can't get None In-Reply-To: <3dc9bcf00710181452g252a364cw637141b093570b1@mail.gmail.com> References: <3dc9bcf00710181452g252a364cw637141b093570b1@mail.gmail.com> Message-ID: <4717D7BA.50109@lindenlab.com> Matthew Scouten wrote: > I want to return None from a c++ function. > I have googled for how to do this with no good results. > How do I get an object with None in c++? That baffled me for a long time too. Try just object(). From amohr at pixar.com Fri Oct 19 00:04:23 2007 From: amohr at pixar.com (Alex Mohr) Date: Thu, 18 Oct 2007 15:04:23 -0700 Subject: [C++-sig] I can't get None In-Reply-To: <3dc9bcf00710181452g252a364cw637141b093570b1@mail.gmail.com> References: <3dc9bcf00710181452g252a364cw637141b093570b1@mail.gmail.com> Message-ID: <4717D867.3040201@pixar.com> > I want to return None from a c++ function. > I have googled for how to do this with no good results. > How do I get an object with None in c++? boost::python::object none; Alex From seefeld at sympatico.ca Fri Oct 19 00:06:37 2007 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 18 Oct 2007 18:06:37 -0400 Subject: [C++-sig] I can't get None In-Reply-To: <3dc9bcf00710181452g252a364cw637141b093570b1@mail.gmail.com> References: <3dc9bcf00710181452g252a364cw637141b093570b1@mail.gmail.com> Message-ID: <4717D8ED.2020902@sympatico.ca> Matthew Scouten wrote: > I want to return None from a c++ function. > I have googled for how to do this with no good results. > How do I get an object with None in c++? return boost::python::object(); HTH, Stefan -- ...ich hab' noch einen Koffer in Berlin... From matthew.scouten at gmail.com Fri Oct 19 18:38:09 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Fri, 19 Oct 2007 11:38:09 -0500 Subject: [C++-sig] stuffing a PyObject into a object Message-ID: <3dc9bcf00710190938h4e641d9bwb7118c20c1cb707f@mail.gmail.com> Right, so.... I've got a void* that I happen to know is really a PyObject*. (how do i know that you ask? It was handed to me by python and tunneled through a 3rd party c++ library that promised not to mess with it.) I need to make it back into a boost::python::object so I can hand it back to python. I googled for how to do this and came across: http://osdir.com/ml/python.c++/2002-12/msg00286.html where I found the following recommendation: boost::python::handle<> h(boost::python::allow_null(PyIter_Next(x))); if (!h.get()) break; // end of iteration boost::python::object o(h); I can understand this except for a couple of things, What is the PyIter_Next there for? demonstration purposes? or is it an essential part of the conversion? Same question for that whole second line. will 'allow_null' make a 'None' out of a null pointer? or do some other crazy thing? more to the point, will this code work: object foo(void* callbackID == NULL) { boost::python::handle<> h(boost::python::allow_null((PyObject*)callbackID)) return boost::python::object o(h); } I am trying to understand what is going on, and not just fall into guess and check programming. From lloyd at fusion.net.nz Sat Oct 20 01:43:44 2007 From: lloyd at fusion.net.nz (Lloyd Weehuizen) Date: Sat, 20 Oct 2007 12:43:44 +1300 Subject: [C++-sig] stuffing a PyObject into a object In-Reply-To: <3dc9bcf00710190938h4e641d9bwb7118c20c1cb707f@mail.gmail.com> References: <3dc9bcf00710190938h4e641d9bwb7118c20c1cb707f@mail.gmail.com> Message-ID: <47194130.9090609@fusion.net.nz> Hi Matthew I'm not sure why the code you found suggests a PyIter_Next, I've never used that myself. I'm guessing it was pulled from an iteration example at one point and lost its context. I do my conversions like this: python::object(python::handle<>(python::borrowed(x))) From what I can tell, allow_null does not return a python None, it simply allows null to pass through the system. After looking through the boost source, it looks like handle converts the NULL to a None when necessary (See handle.hpp:256 (get_managed_object)). Cheers, Lloyd Matthew Scouten wrote: > Right, so.... > I've got a void* that I happen to know is really a PyObject*. (how do > i know that you ask? It was handed to me by python and tunneled > through a 3rd party c++ library that promised not to mess with it.) I > need to make it back into a boost::python::object so I can hand it > back to python. > > I googled for how to do this and came across: > http://osdir.com/ml/python.c++/2002-12/msg00286.html > > where I found the following recommendation: > > boost::python::handle<> h(boost::python::allow_null(PyIter_Next(x))); > if (!h.get()) break; // end of iteration > boost::python::object o(h); > > I can understand this except for a couple of things, > > What is the PyIter_Next there for? demonstration purposes? or is it an > essential part of the conversion? Same question for that whole second > line. > > will 'allow_null' make a 'None' out of a null pointer? or do some > other crazy thing? > > more to the point, will this code work: > > object foo(void* callbackID == NULL) > { > boost::python::handle<> h(boost::python::allow_null((PyObject*)callbackID)) > return boost::python::object o(h); > } > > I am trying to understand what is going on, and not just fall into > guess and check programming. > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig From tsandler at seas.upenn.edu Sun Oct 21 21:26:28 2007 From: tsandler at seas.upenn.edu (ted sandler) Date: Sun, 21 Oct 2007 15:26:28 -0400 Subject: [C++-sig] can't get Boost.Python tutorial's "Hello World" example to work (on linux) Message-ID: Hi all, I am running linux, and although the Boost.Python "Quickstart" example works fine, I am not able to get the Boost.Python "Hello World" example working. The quickstart example is located here http://www.boost.org/libs/python/doc/building.html. The hello-world example is located here: http://www.boost.org/libs/python/doc/tutorial/doc/html/python/hello.html. There are problems with the documentation on the hello-world web page (I guess it's out of date). The example files in the Boost-distribution are different from those described in the "hello-world" tutorial. Specifically, the Boost distribution contains a "Jamroot" file while the web page discusses both a "Jamfile" and a "Jamrules" file (whose hyperlink is broken). Anyway, when I cd to the "hello-world" example directory and type bjam at the prompt, bjam fails with the error message I've listed below. Any help getting me up and running here would be great! Thanks a bunch, -Ted Jamroot:17: in modules.load rule python-extension unknown in module Jamfile. /home/ted/boost_1_34_1/tools/build/v2/build/project.jam:312: in load-jamfile /home/ted/boost_1_34_1/tools/build/v2/build/project.jam:68: in load /home/ted/boost_1_34_1/tools/build/v2/build/project.jam:170: in project.find /home/ted/boost_1_34_1/tools/build/v2/build-system.jam:237: in load /home/ted/boost_1_34_1/libs/python/example/../../../tools/build/v2/kernel/modules.jam:261: in import /home/ted/boost_1_34_1/libs/python/example/../../../tools/build/v2/kernel/bootstrap.jam:132: in boost-build /home/ted/boost_1_34_1/libs/python/example/boost-build.jam:7: in module scope From Chang_Chen at sonic.com Mon Oct 22 09:05:17 2007 From: Chang_Chen at sonic.com (Chang Chen) Date: Mon, 22 Oct 2007 15:05:17 +0800 Subject: [C++-sig] To Roman Yakovenko - a question about boost python In-Reply-To: <51C471E6CBEC8148A08E065690F4DBDF01679895@SHAEXC01.ent.sonic.com> Message-ID: <51C471E6CBEC8148A08E065690F4DBDF016CC910@SHAEXC01.ent.sonic.com> Hi Roman Yakovenko Do you think what I think on out parameter is ok or not? Any suggestion? - Chang -----Original Message----- From: c++-sig-bounces+chang_chen=sonic.com at python.org [mailto:c++-sig-bounces+chang_chen=sonic.com at python.org] On Behalf Of Chang Chen Sent: Wednesday, October 17, 2007 11:38 AM To: c++-sig at python.org Subject: [C++-sig] a question about boost python I know we need define a wrapper, but our function signature is quite regular. i.e. only the last parameter is output parameter, so I want to write a template, so that such wrapper can be easily written. Our function definition looks like: void function1(int t1, float t2, string& t3) ; I want to define a template: template struct FunctionConvert< Return (*) ( T1 , T2, TOUT& ) > { typedef functionT Return (*) ( T1 , T2, TOUT& ); static TOUT run(functionT P,const T1& t1, const T2& t2) { TOUT out; P(t1,t2,out); return out; } } But I do not know how to integrate it with boost python :(. - Chang _______________________________________________ C++-sig mailing list C++-sig at python.org http://mail.python.org/mailman/listinfo/c++-sig From Chang_Chen at sonic.com Mon Oct 22 13:08:14 2007 From: Chang_Chen at sonic.com (Chang Chen) Date: Mon, 22 Oct 2007 19:08:14 +0800 Subject: [C++-sig] Wrapping out parameter for python access Message-ID: <51C471E6CBEC8148A08E065690F4DBDF016CCA1D@SHAEXC01.ent.sonic.com> Hi all This is a classical issue in boost python. I.e. removeing an argument from the function definition and adding the "returned", by the original function, value to the return statement of the function-wrapper For example : The original function is: inline void hello_world( std::string& hw ){ hw = "hello world!"; } And the wrapper is: inline std::string hello_world_wrapper() { std:string temp; ::hello_world(temp); Return temp; } Py++ can help us to generate such wrapper, see http://language-binding.net/pyplusplus/documentation/functions/transform ation/built_in/output.html But in this thread (http://mail.python.org/pipermail/c++-sig/2005-June/009097.html ), Dave provided a start to write a wrapping template. In My case, only last parameter is out parameter and whether function parameter count does not matter. The function signature looks like: Return function (T1 t1, T2 t2, TOUT& out); How to write a template for such function and integrate into def? Any suggestion? -Chang From grh at mur.at Mon Oct 22 18:03:38 2007 From: grh at mur.at (Georg Holzmann) Date: Mon, 22 Oct 2007 18:03:38 +0200 Subject: [C++-sig] datastructure to numpy and back In-Reply-To: References: <4713AC69.4000804@mur.at> <4714DCAD.6050300@mur.at> Message-ID: <471CC9DA.2010907@mur.at> Hallo! > I've written a swig wrapper around a structure that could be used for > wrapping anything that needs to expose the __array_struct__ property > (didn't had the time to try Boost with Albert's wrappers). It is not > available on the net, but it is based on some mails that were sent here > and on the Pyrex example for the array interface. Thanks, I looked now through quite some SWIG examples and I was able to get a matrix/array from numpy into C++ (with the very good documentated examples in numpy-svn/numpy/doc/swig). However, I did not manage to get an array out of C++ to python without copying so far. In the examples cited above it's only shown how to generate a new one dimensional array and return that. Do you maybe have some links (from the mails here and on) where these features are explained ? Or modules which are examples for such use-cases ? Thanks for any hint, LG Georg From matthew.scouten at gmail.com Mon Oct 22 19:56:13 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Mon, 22 Oct 2007 12:56:13 -0500 Subject: [C++-sig] Comparing to None on the c++ side Message-ID: <3dc9bcf00710221056n4ca21944sea68faaa38960b1@mail.gmail.com> Right, so... Python just called a c++ function and passed an object of some sort. I want to know if it happens to be a None, so I can take special precautions to avoid disaster. I am trying to use something like: void foo(object o) { if( object() == o ) { //Make 3rdparty c++ lib call that prevents //Sky from falling } else { //tell 3rdparty c++ lib to //try to use o to prop up sky... } } This does not seem to be working like I expected (the sky falls anyway) So me question: is object() == o a valid and reliable way to test for None? If not, how should I be doing it? It is possible that the problem is in 3rdparty c++ lib or my understanding thereof, but I am trying to eliminate the other possibilities. From shrikantvc at gmail.com Thu Oct 25 08:52:24 2007 From: shrikantvc at gmail.com (Shrikant Chikhalkar) Date: Thu, 25 Oct 2007 12:22:24 +0530 Subject: [C++-sig] failed in PyImport_Import() Message-ID: <87de5f460710242352w5b57dc4djbcfba96ccf0f3578@mail.gmail.com> Hi, i am tring to call python function from 'C' program. i get NULL value return by PyImport_Import() following is the code. code is copied from http://www.codeproject.com/cpp/embedpython_1.asp following file is saved as call_function.c /************************************************************************************************************/ // call_function.c - A sample of calling // python functions from C code // #include int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc, *pValue; if (argc < 3) { printf("Usage: exe_name python_source function_name\n"); return 1; } // Initialize the Python Interpreter Py_Initialize(); // Build the name object pName = PyString_FromString(argv[1]); // Load the module object pModule = PyImport_Import(pName); // pDict is a borrowed reference pDict = PyModule_GetDict(pModule); // pFunc is also a borrowed reference pFunc = PyDict_GetItemString(pDict, argv[2]); if (PyCallable_Check(pFunc)) { PyObject_CallObject(pFunc, NULL); } else { PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pName); // Finish the Python Interpreter Py_Finalize(); return 0; } /************************************************************************************************************/ python file saved as py_function.py /************************************************************************************************************/ '''py_function.py - Python source designed to ''' '''demonstrate the use of python embedding''' def multiply(): c = 12345*6789 print 'The result of 12345 x 6789 :', c return c /************************************************************************************************************/ $gcc -g call_function.c -lpython2.5 -ocall_function $./call_function py_function.py multiply i get following output ImportError: No module named py_function Failed to load "py_function" when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. can any one please find out the error that i am doing. -- Shrikant -------------- next part -------------- An HTML attachment was scrubbed... URL: From gjcarneiro at gmail.com Thu Oct 25 09:21:19 2007 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Thu, 25 Oct 2007 08:21:19 +0100 Subject: [C++-sig] failed in PyImport_Import() In-Reply-To: <87de5f460710242352w5b57dc4djbcfba96ccf0f3578@mail.gmail.com> References: <87de5f460710242352w5b57dc4djbcfba96ccf0f3578@mail.gmail.com> Message-ID: On 25/10/2007, Shrikant Chikhalkar wrote: > > Hi, > > i am tring to call python function from 'C' program. i get NULL value > return by PyImport_Import() > > following is the code. code is copied from > http://www.codeproject.com/cpp/embedpython_1.asp > > following file is saved as > > call_function.c > > /************************************************************************************************************/ > > > // call_function.c - A sample of calling > // python functions from C code > > // > #include > > int main(int argc, char *argv[]) > { > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > if (argc < 3) > { > printf("Usage: exe_name python_source function_name\n" > ); > return 1; > } > > // Initialize the Python Interpreter > Py_Initialize(); > > > // Build the name object > pName = PyString_FromString(argv[1]); > > // Load the module object > pModule = PyImport_Import(pName); > > > // pDict is a borrowed reference > pDict = PyModule_GetDict(pModule); > > // pFunc is also a borrowed reference > pFunc = PyDict_GetItemString(pDict, argv[ > 2]); > > if (PyCallable_Check(pFunc)) > { > PyObject_CallObject(pFunc, NULL); > } else > { > > PyErr_Print(); > } > > // Clean up > Py_DECREF(pModule); > Py_DECREF(pName); > > // Finish the Python Interpreter > > Py_Finalize(); > > return 0; > } > > /************************************************************************************************************/ > > python file saved as > > py_function.py > > > /************************************************************************************************************/ > > '''py_function.py - Python source designed to ''' > '''demonstrate the use of python embedding''' > > def multiply(): > c = 12345*6789 > print 'The result of 12345 x 6789 :', c > > > > return c > > > /************************************************************************************************************/ > > $gcc -g call_function.c -lpython2.5 -ocall_function > $./call_function py_function.py multiply Shouldn't this be: $./call_function py_function multiply I.e., you the module name should not have a .py extension. i get following output > > ImportError: No module named py_function > Failed to load "py_function" > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > can any one please find out the error that i am doing. > > -- > Shrikant > > > _______________________________________________ > 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 shrikantvc at gmail.com Thu Oct 25 13:03:42 2007 From: shrikantvc at gmail.com (Shrikant Chikhalkar) Date: Thu, 25 Oct 2007 16:33:42 +0530 Subject: [C++-sig] C++-sig Digest, Vol 51, Issue 25 In-Reply-To: References: Message-ID: <87de5f460710250403q311e8fd1q61de04dc7b935f88@mail.gmail.com> Hi, thanks for the reply. that i have already tried. Still i am getting same error. could you please give some pointer that where i am doing wrong. thanks Shrikant On 10/25/07, c++-sig-request at python.org wrote: > > Send C++-sig mailing list submissions to > c++-sig at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/c++-sig > or, via email, send a message with subject or body 'help' to > c++-sig-request at python.org > > You can reach the person managing the list at > c++-sig-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of C++-sig digest..." > > > Today's Topics: > > 1. failed in PyImport_Import() (Shrikant Chikhalkar) > 2. Re: failed in PyImport_Import() (Gustavo Carneiro) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 25 Oct 2007 12:22:24 +0530 > From: "Shrikant Chikhalkar" > Subject: [C++-sig] failed in PyImport_Import() > To: c++-sig at python.org > Message-ID: > <87de5f460710242352w5b57dc4djbcfba96ccf0f3578 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi, > > i am tring to call python function from 'C' program. i get NULL value > return > by PyImport_Import() > > following is the code. code is copied from > http://www.codeproject.com/cpp/embedpython_1.asp > > following file is saved as > > call_function.c > > > /************************************************************************************************************/ > > // call_function.c - A sample of calling > // python functions from C code > // > #include > > int main(int argc, char *argv[]) > { > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > if (argc < 3) > { > printf("Usage: exe_name python_source function_name\n"); > return 1; > } > > // Initialize the Python Interpreter > Py_Initialize(); > > // Build the name object > pName = PyString_FromString(argv[1]); > > // Load the module object > pModule = PyImport_Import(pName); > > // pDict is a borrowed reference > pDict = PyModule_GetDict(pModule); > > // pFunc is also a borrowed reference > pFunc = PyDict_GetItemString(pDict, argv[2]); > > if (PyCallable_Check(pFunc)) > { > PyObject_CallObject(pFunc, NULL); > } else > { > PyErr_Print(); > } > > // Clean up > Py_DECREF(pModule); > Py_DECREF(pName); > > // Finish the Python Interpreter > Py_Finalize(); > > return 0; > } > > > /************************************************************************************************************/ > python file saved as > > py_function.py > > > /************************************************************************************************************/ > > '''py_function.py - Python source designed to ''' > '''demonstrate the use of python embedding''' > > def multiply(): > c = 12345*6789 > print 'The result of 12345 x 6789 :', c > > > return c > > > /************************************************************************************************************/ > > $gcc -g call_function.c -lpython2.5 -ocall_function > $./call_function py_function.py multiply > > i get following output > > ImportError: No module named py_function > Failed to load "py_function" > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > can any one please find out the error that i am doing. > > -- > Shrikant > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/c++-sig/attachments/20071025/e3ca2dfd/attachment-0001.htm > > ------------------------------ > > Message: 2 > Date: Thu, 25 Oct 2007 08:21:19 +0100 > From: "Gustavo Carneiro" > Subject: Re: [C++-sig] failed in PyImport_Import() > To: "Development of Python/C++ integration" > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > On 25/10/2007, Shrikant Chikhalkar wrote: > > > > Hi, > > > > i am tring to call python function from 'C' program. i get NULL value > > return by PyImport_Import() > > > > following is the code. code is copied from > > http://www.codeproject.com/cpp/embedpython_1.asp > > > > following file is saved as > > > > call_function.c > > > > > /************************************************************************************************************/ > > > > > > // call_function.c - A sample of calling > > // python functions from C code > > > > // > > #include > > > > int main(int argc, char *argv[]) > > { > > > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > > > if (argc < 3) > > { > > printf("Usage: exe_name python_source function_name\n" > > ); > > return 1; > > } > > > > // Initialize the Python Interpreter > > Py_Initialize(); > > > > > > // Build the name object > > pName = PyString_FromString(argv[1]); > > > > // Load the module object > > pModule = PyImport_Import(pName); > > > > > > // pDict is a borrowed reference > > pDict = PyModule_GetDict(pModule); > > > > // pFunc is also a borrowed reference > > pFunc = PyDict_GetItemString(pDict, argv[ > > 2]); > > > > if (PyCallable_Check(pFunc)) > > { > > PyObject_CallObject(pFunc, NULL); > > } else > > { > > > > PyErr_Print(); > > } > > > > // Clean up > > Py_DECREF(pModule); > > Py_DECREF(pName); > > > > // Finish the Python Interpreter > > > > Py_Finalize(); > > > > return 0; > > } > > > > > /************************************************************************************************************/ > > > > python file saved as > > > > py_function.py > > > > > > > /************************************************************************************************************/ > > > > '''py_function.py - Python source designed to ''' > > '''demonstrate the use of python embedding''' > > > > def multiply(): > > c = 12345*6789 > > print 'The result of 12345 x 6789 :', c > > > > > > > > return c > > > > > > > /************************************************************************************************************/ > > > > $gcc -g call_function.c -lpython2.5 -ocall_function > > $./call_function py_function.py multiply > > > Shouldn't this be: > $./call_function py_function multiply > > I.e., you the module name should not have a .py extension. > > i get following output > > > > ImportError: No module named py_function > > Failed to load "py_function" > > > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > > > can any one please find out the error that i am doing. > > > > -- > > Shrikant > > > > > > _______________________________________________ > > 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: > http://mail.python.org/pipermail/c++-sig/attachments/20071025/0fc3b1ea/attachment-0001.htm > > ------------------------------ > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > > > End of C++-sig Digest, Vol 51, Issue 25 > *************************************** > -- Shrikant Chikhalkar +91 9850991554 -------------- next part -------------- An HTML attachment was scrubbed... URL: From shrikantvc at gmail.com Thu Oct 25 13:24:02 2007 From: shrikantvc at gmail.com (Shrikant Chikhalkar) Date: Thu, 25 Oct 2007 16:54:02 +0530 Subject: [C++-sig] C++-sig Digest, Vol 51, Issue 25 In-Reply-To: References: Message-ID: <87de5f460710250424k1ef321aei273ae019035bf476@mail.gmail.com> Hi, I have also check that "py_function.py" is in the same directory. i have some doubt 1) do we need to install "py_function" module before calling multiply function from that. ( install means python -m py_function) 2) individually multiply function is working fine on python prompt. 3) I am using python2.5 headers I know some where i had make a mistake. please help me to locate that thanks Shrikant On 10/25/07, c++-sig-request at python.org wrote: > > Send C++-sig mailing list submissions to > c++-sig at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/c++-sig > or, via email, send a message with subject or body 'help' to > c++-sig-request at python.org > > You can reach the person managing the list at > c++-sig-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of C++-sig digest..." > > > Today's Topics: > > 1. failed in PyImport_Import() (Shrikant Chikhalkar) > 2. Re: failed in PyImport_Import() (Gustavo Carneiro) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 25 Oct 2007 12:22:24 +0530 > From: "Shrikant Chikhalkar" > Subject: [C++-sig] failed in PyImport_Import() > To: c++-sig at python.org > Message-ID: > <87de5f460710242352w5b57dc4djbcfba96ccf0f3578 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi, > > i am tring to call python function from 'C' program. i get NULL value > return > by PyImport_Import() > > following is the code. code is copied from > http://www.codeproject.com/cpp/embedpython_1.asp > > following file is saved as > > call_function.c > > > /************************************************************************************************************/ > > // call_function.c - A sample of calling > // python functions from C code > // > #include > > int main(int argc, char *argv[]) > { > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > if (argc < 3) > { > printf("Usage: exe_name python_source function_name\n"); > return 1; > } > > // Initialize the Python Interpreter > Py_Initialize(); > > // Build the name object > pName = PyString_FromString(argv[1]); > > // Load the module object > pModule = PyImport_Import(pName); > > // pDict is a borrowed reference > pDict = PyModule_GetDict(pModule); > > // pFunc is also a borrowed reference > pFunc = PyDict_GetItemString(pDict, argv[2]); > > if (PyCallable_Check(pFunc)) > { > PyObject_CallObject(pFunc, NULL); > } else > { > PyErr_Print(); > } > > // Clean up > Py_DECREF(pModule); > Py_DECREF(pName); > > // Finish the Python Interpreter > Py_Finalize(); > > return 0; > } > > > /************************************************************************************************************/ > python file saved as > > py_function.py > > > /************************************************************************************************************/ > > '''py_function.py - Python source designed to ''' > '''demonstrate the use of python embedding''' > > def multiply(): > c = 12345*6789 > print 'The result of 12345 x 6789 :', c > > > return c > > > /************************************************************************************************************/ > > $gcc -g call_function.c -lpython2.5 -ocall_function > $./call_function py_function.py multiply > > i get following output > > ImportError: No module named py_function > Failed to load "py_function" > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > can any one please find out the error that i am doing. > > -- > Shrikant > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/c++-sig/attachments/20071025/e3ca2dfd/attachment-0001.htm > > ------------------------------ > > Message: 2 > Date: Thu, 25 Oct 2007 08:21:19 +0100 > From: "Gustavo Carneiro" > Subject: Re: [C++-sig] failed in PyImport_Import() > To: "Development of Python/C++ integration" > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > On 25/10/2007, Shrikant Chikhalkar wrote: > > > > Hi, > > > > i am tring to call python function from 'C' program. i get NULL value > > return by PyImport_Import() > > > > following is the code. code is copied from > > http://www.codeproject.com/cpp/embedpython_1.asp > > > > following file is saved as > > > > call_function.c > > > > > /************************************************************************************************************/ > > > > > > // call_function.c - A sample of calling > > // python functions from C code > > > > // > > #include > > > > int main(int argc, char *argv[]) > > { > > > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > > > if (argc < 3) > > { > > printf("Usage: exe_name python_source function_name\n" > > ); > > return 1; > > } > > > > // Initialize the Python Interpreter > > Py_Initialize(); > > > > > > // Build the name object > > pName = PyString_FromString(argv[1]); > > > > // Load the module object > > pModule = PyImport_Import(pName); > > > > > > // pDict is a borrowed reference > > pDict = PyModule_GetDict(pModule); > > > > // pFunc is also a borrowed reference > > pFunc = PyDict_GetItemString(pDict, argv[ > > 2]); > > > > if (PyCallable_Check(pFunc)) > > { > > PyObject_CallObject(pFunc, NULL); > > } else > > { > > > > PyErr_Print(); > > } > > > > // Clean up > > Py_DECREF(pModule); > > Py_DECREF(pName); > > > > // Finish the Python Interpreter > > > > Py_Finalize(); > > > > return 0; > > } > > > > > /************************************************************************************************************/ > > > > python file saved as > > > > py_function.py > > > > > > > /************************************************************************************************************/ > > > > '''py_function.py - Python source designed to ''' > > '''demonstrate the use of python embedding''' > > > > def multiply(): > > c = 12345*6789 > > print 'The result of 12345 x 6789 :', c > > > > > > > > return c > > > > > > > /************************************************************************************************************/ > > > > $gcc -g call_function.c -lpython2.5 -ocall_function > > $./call_function py_function.py multiply > > > Shouldn't this be: > $./call_function py_function multiply > > I.e., you the module name should not have a .py extension. > > i get following output > > > > ImportError: No module named py_function > > Failed to load "py_function" > > > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > > > can any one please find out the error that i am doing. > > > > -- > > Shrikant > > > > > > _______________________________________________ > > 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: > http://mail.python.org/pipermail/c++-sig/attachments/20071025/0fc3b1ea/attachment-0001.htm > > ------------------------------ > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > > > End of C++-sig Digest, Vol 51, Issue 25 > *************************************** > -- Shrikant Chikhalkar +91 9850991554 -------------- next part -------------- An HTML attachment was scrubbed... URL: From don.j.olmstead at gmail.com Fri Oct 26 00:36:37 2007 From: don.j.olmstead at gmail.com (Don) Date: Thu, 25 Oct 2007 22:36:37 +0000 (UTC) Subject: [C++-sig] =?utf-8?q?Using_an_intrusive=5Fptr_with_a_noncopyable_m?= =?utf-8?q?ember_variable?= Message-ID: Hello all, Just starting to try using boost python for exposing some code I've written. Essentially I have a class Object that has a protected constructor, that is derived by various other classes. This class does its own reference counting via intrusive_ptr. Because it does its own reference counting and for thread safety I have a mutex that is entered when changing the reference count. So the header file for the Object class, with unrelated functionality stripped out is. namespace Shade { class Object { protected: Object(); public: virtual ~Object(); // Reference counting public: void incrementReferences(); void decrementReferences(); unsigned int getNumberOfReferences() const; private: /** Number of references to the Object */ unsigned int numReferences; /** * Mutex for the reference counting system. * * Assures that a pointer isn't accidently deleted or * left dangling when accessed by multiple threads. */ boost::mutex mutexRefCount; } ; /** Smart Pointer for the Object class */ typedef boost::intrusive_ptr ObjectPtr; #include "ShadeObject.inl" } void intrusive_ptr_add_ref(Shade::Object* object); void intrusive_ptr_release(Shade::Object* object); I expose it to Python using the following code BOOST_PYTHON_MODULE(Shade) { python::class_("Object", python::no_init) // class .def's ; // Uninteresting dummy test class python::class_ >("DummyObject"); } So in C++ if I do DummyObjectPtr test1 = DummyObject(); DummyObjectPtr test2 = test1; std::cout << test1->getNumberOfReferences() << std::endl; The console will say 2 Now if I do the same in Python test1 = DummyObject() test2 = test1 print test1.getNumberOfReferences() The console will say 1 The Object wont attempt to delete itself until both test1 and test2 are set to something else so Python must be keeping a reference count. It would just be nice to know what the total number of references are across Python and C++. Any ideas? From steven.wyckoff at gmail.com Fri Oct 26 06:49:49 2007 From: steven.wyckoff at gmail.com (Steven Wyckoff) Date: Thu, 25 Oct 2007 22:49:49 -0600 Subject: [C++-sig] failed in PyImport_Import() In-Reply-To: <87de5f460710242352w5b57dc4djbcfba96ccf0f3578@mail.gmail.com> References: <87de5f460710242352w5b57dc4djbcfba96ccf0f3578@mail.gmail.com> Message-ID: Based on reading the code, I cannot see why it would be failing to create the module. Having gone through a similar process not too long ago, there are a couple gotchas that I ran into. First is the .py in the module name: you need it in the file name, and not in the module name (just like importing within python). Another is that depending on your debugger, it may be running the program in a different location than the executable is located (for example VS does this I know). You had mentioned that your py_function works properly in a python prompt but just as a heads up, we had problems where a syntax error in the python file would cause cryptic module loading errors. You may also want to check that there is not an old version of the .pyc file sitting around confusing things. It looks like you are using PyErr_Print() and getting some info back from it, I found that to be very helpful, even more so once the scripts were running. Python should look for a module in the directory where it is being run from, however, if you think that the issue is that python is not finding your file, you can add an arbitrary directory on your computer to the module search path within your program: PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\"your\path\here")"); You could also try using PyRun_SimpleString("import py_function") to try importing the module just to try to isolate the issue. I hope that your problem is the same as one of ours and good luck! Steve Wyckoff Shrikant Chikhalkar wrote: > Hi, > > i am tring to call python function from 'C' program. i get NULL value > return by PyImport_Import() > > following is the code. code is copied from > http://www.codeproject.com/cpp/embedpython_1.asp > > following file is saved as > > call_function.c > > /************************************************************************************************************/ > > > // call_function.c - A sample of calling > // python functions from C code > > // > #include > > int main(int argc, char *argv[]) > { > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > if (argc < 3) > { > printf("Usage: exe_name python_source function_name\n" > ); > return 1; > } > > // Initialize the Python Interpreter > Py_Initialize(); > > > // Build the name object > pName = PyString_FromString(argv[1]); > > // Load the module object > pModule = PyImport_Import(pName); > > > // pDict is a borrowed reference > pDict = PyModule_GetDict(pModule); > > // pFunc is also a borrowed reference > pFunc = PyDict_GetItemString(pDict, argv[ > 2]); > > if (PyCallable_Check(pFunc)) > { > PyObject_CallObject(pFunc, NULL); > } else > { > > PyErr_Print(); > } > > // Clean up > Py_DECREF(pModule); > Py_DECREF(pName); > > // Finish the Python Interpreter > > Py_Finalize(); > > return 0; > } > > /************************************************************************************************************/ > > python file saved as > > py_function.py > > /************************************************************************************************************/ > > '''py_function.py - Python source designed to ''' > '''demonstrate the use of python embedding''' > > def multiply(): > c = 12345*6789 > print 'The result of 12345 x 6789 :', c > > > > return c > > /************************************************************************************************************/ > > $gcc -g call_function.c -lpython2.5 -ocall_function > $./call_function py_function.py multiply > > i get following output > > ImportError: No module named py_function > Failed to load "py_function" > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > can any one please find out the error that i am doing. > > -- > Shrikant > > > ------------------------------------------------------------------------ > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig From shrikantvc at gmail.com Fri Oct 26 12:27:00 2007 From: shrikantvc at gmail.com (Shrikant Chikhalkar) Date: Fri, 26 Oct 2007 15:57:00 +0530 Subject: [C++-sig] C++-sig Digest, Vol 51, Issue 26 In-Reply-To: References: Message-ID: <87de5f460710260327l1e3574c2s9234978669888ac8@mail.gmail.com> I got solution for the problem. using root credentials run following command on shell prompt $python2 setup.py install where setup.py would be from distutils.core import setup setup(name='xxx', version='1.0', py_modules=['py_function'], ) thanks shrikant On 10/25/07, c++-sig-request at python.org wrote: > > Send C++-sig mailing list submissions to > c++-sig at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/c++-sig > or, via email, send a message with subject or body 'help' to > c++-sig-request at python.org > > You can reach the person managing the list at > c++-sig-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of C++-sig digest..." > > > Today's Topics: > > 1. Re: C++-sig Digest, Vol 51, Issue 25 (Shrikant Chikhalkar) > 2. Re: C++-sig Digest, Vol 51, Issue 25 (Shrikant Chikhalkar) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 25 Oct 2007 16:33:42 +0530 > From: "Shrikant Chikhalkar" > Subject: Re: [C++-sig] C++-sig Digest, Vol 51, Issue 25 > To: c++-sig at python.org > Message-ID: > <87de5f460710250403q311e8fd1q61de04dc7b935f88 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi, > thanks for the reply. > that i have already tried. Still i am getting same error. could you please > give some pointer that where i am doing wrong. > > thanks > Shrikant > > > On 10/25/07, c++-sig-request at python.org > wrote: > > > > Send C++-sig mailing list submissions to > > c++-sig at python.org > > > > To subscribe or unsubscribe via the World Wide Web, visit > > http://mail.python.org/mailman/listinfo/c++-sig > > or, via email, send a message with subject or body 'help' to > > c++-sig-request at python.org > > > > You can reach the person managing the list at > > c++-sig-owner at python.org > > > > When replying, please edit your Subject line so it is more specific > > than "Re: Contents of C++-sig digest..." > > > > > > Today's Topics: > > > > 1. failed in PyImport_Import() (Shrikant Chikhalkar) > > 2. Re: failed in PyImport_Import() (Gustavo Carneiro) > > > > > > ---------------------------------------------------------------------- > > > > Message: 1 > > Date: Thu, 25 Oct 2007 12:22:24 +0530 > > From: "Shrikant Chikhalkar" > > Subject: [C++-sig] failed in PyImport_Import() > > To: c++-sig at python.org > > Message-ID: > > <87de5f460710242352w5b57dc4djbcfba96ccf0f3578 at mail.gmail.com> > > Content-Type: text/plain; charset="iso-8859-1" > > > > Hi, > > > > i am tring to call python function from 'C' program. i get NULL value > > return > > by PyImport_Import() > > > > following is the code. code is copied from > > http://www.codeproject.com/cpp/embedpython_1.asp > > > > following file is saved as > > > > call_function.c > > > > > > > /************************************************************************************************************/ > > > > // call_function.c - A sample of calling > > // python functions from C code > > // > > #include > > > > int main(int argc, char *argv[]) > > { > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > > > if (argc < 3) > > { > > printf("Usage: exe_name python_source function_name\n"); > > return 1; > > } > > > > // Initialize the Python Interpreter > > Py_Initialize(); > > > > // Build the name object > > pName = PyString_FromString(argv[1]); > > > > // Load the module object > > pModule = PyImport_Import(pName); > > > > // pDict is a borrowed reference > > pDict = PyModule_GetDict(pModule); > > > > // pFunc is also a borrowed reference > > pFunc = PyDict_GetItemString(pDict, argv[2]); > > > > if (PyCallable_Check(pFunc)) > > { > > PyObject_CallObject(pFunc, NULL); > > } else > > { > > PyErr_Print(); > > } > > > > // Clean up > > Py_DECREF(pModule); > > Py_DECREF(pName); > > > > // Finish the Python Interpreter > > Py_Finalize(); > > > > return 0; > > } > > > > > > > /************************************************************************************************************/ > > python file saved as > > > > py_function.py > > > > > > > /************************************************************************************************************/ > > > > '''py_function.py - Python source designed to ''' > > '''demonstrate the use of python embedding''' > > > > def multiply(): > > c = 12345*6789 > > print 'The result of 12345 x 6789 :', c > > > > > > return c > > > > > > > /************************************************************************************************************/ > > > > $gcc -g call_function.c -lpython2.5 -ocall_function > > $./call_function py_function.py multiply > > > > i get following output > > > > ImportError: No module named py_function > > Failed to load "py_function" > > > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > > > can any one please find out the error that i am doing. > > > > -- > > Shrikant > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > > http://mail.python.org/pipermail/c++-sig/attachments/20071025/e3ca2dfd/attachment-0001.htm > > > > ------------------------------ > > > > Message: 2 > > Date: Thu, 25 Oct 2007 08:21:19 +0100 > > From: "Gustavo Carneiro" > > Subject: Re: [C++-sig] failed in PyImport_Import() > > To: "Development of Python/C++ integration" > > Message-ID: > > > > Content-Type: text/plain; charset="utf-8" > > > > On 25/10/2007, Shrikant Chikhalkar wrote: > > > > > > Hi, > > > > > > i am tring to call python function from 'C' program. i get NULL value > > > return by PyImport_Import() > > > > > > following is the code. code is copied from > > > http://www.codeproject.com/cpp/embedpython_1.asp > > > > > > following file is saved as > > > > > > call_function.c > > > > > > > > > /************************************************************************************************************/ > > > > > > > > > // call_function.c - A sample of calling > > > // python functions from C code > > > > > > // > > > #include > > > > > > int main(int argc, char *argv[]) > > > { > > > > > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > > > > > if (argc < 3) > > > { > > > printf("Usage: exe_name python_source function_name\n" > > > ); > > > return 1; > > > } > > > > > > // Initialize the Python Interpreter > > > Py_Initialize(); > > > > > > > > > // Build the name object > > > pName = PyString_FromString(argv[1]); > > > > > > // Load the module object > > > pModule = PyImport_Import(pName); > > > > > > > > > // pDict is a borrowed reference > > > pDict = PyModule_GetDict(pModule); > > > > > > // pFunc is also a borrowed reference > > > pFunc = PyDict_GetItemString(pDict, argv[ > > > 2]); > > > > > > if (PyCallable_Check(pFunc)) > > > { > > > PyObject_CallObject(pFunc, NULL); > > > } else > > > { > > > > > > PyErr_Print(); > > > } > > > > > > // Clean up > > > Py_DECREF(pModule); > > > Py_DECREF(pName); > > > > > > // Finish the Python Interpreter > > > > > > Py_Finalize(); > > > > > > return 0; > > > } > > > > > > > > > /************************************************************************************************************/ > > > > > > python file saved as > > > > > > py_function.py > > > > > > > > > > > > /************************************************************************************************************/ > > > > > > '''py_function.py - Python source designed to ''' > > > '''demonstrate the use of python embedding''' > > > > > > def multiply(): > > > c = 12345*6789 > > > print 'The result of 12345 x 6789 :', c > > > > > > > > > > > > return c > > > > > > > > > > > > /************************************************************************************************************/ > > > > > > $gcc -g call_function.c -lpython2.5 -ocall_function > > > $./call_function py_function.py multiply > > > > > > Shouldn't this be: > > $./call_function py_function multiply > > > > I.e., you the module name should not have a .py extension. > > > > i get following output > > > > > > ImportError: No module named py_function > > > Failed to load "py_function" > > > > > > when i kdbg(debug) it i vet NULL value returned from > PyImport_Import().. > > > > > > can any one please find out the error that i am doing. > > > > > > -- > > > Shrikant > > > > > > > > > _______________________________________________ > > > 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: > > > http://mail.python.org/pipermail/c++-sig/attachments/20071025/0fc3b1ea/attachment-0001.htm > > > > ------------------------------ > > > > _______________________________________________ > > C++-sig mailing list > > C++-sig at python.org > > http://mail.python.org/mailman/listinfo/c++-sig > > > > > > End of C++-sig Digest, Vol 51, Issue 25 > > *************************************** > > > > > > -- > Shrikant Chikhalkar > +91 9850991554 > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/c++-sig/attachments/20071025/63f1ada0/attachment-0001.htm > > ------------------------------ > > Message: 2 > Date: Thu, 25 Oct 2007 16:54:02 +0530 > From: "Shrikant Chikhalkar" > Subject: Re: [C++-sig] C++-sig Digest, Vol 51, Issue 25 > To: c++-sig at python.org > Message-ID: > <87de5f460710250424k1ef321aei273ae019035bf476 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi, > > I have also check that "py_function.py" is in the same directory. > i have some doubt > 1) do we need to install "py_function" module before calling multiply > function from that. ( install means python -m py_function) > 2) individually multiply function is working fine on python prompt. > 3) I am using python2.5 headers > > I know some where i had make a mistake. please help me to locate that > > thanks > Shrikant > > On 10/25/07, c++-sig-request at python.org > wrote: > > > > Send C++-sig mailing list submissions to > > c++-sig at python.org > > > > To subscribe or unsubscribe via the World Wide Web, visit > > http://mail.python.org/mailman/listinfo/c++-sig > > or, via email, send a message with subject or body 'help' to > > c++-sig-request at python.org > > > > You can reach the person managing the list at > > c++-sig-owner at python.org > > > > When replying, please edit your Subject line so it is more specific > > than "Re: Contents of C++-sig digest..." > > > > > > Today's Topics: > > > > 1. failed in PyImport_Import() (Shrikant Chikhalkar) > > 2. Re: failed in PyImport_Import() (Gustavo Carneiro) > > > > > > ---------------------------------------------------------------------- > > > > Message: 1 > > Date: Thu, 25 Oct 2007 12:22:24 +0530 > > From: "Shrikant Chikhalkar" > > Subject: [C++-sig] failed in PyImport_Import() > > To: c++-sig at python.org > > Message-ID: > > <87de5f460710242352w5b57dc4djbcfba96ccf0f3578 at mail.gmail.com> > > Content-Type: text/plain; charset="iso-8859-1" > > > > Hi, > > > > i am tring to call python function from 'C' program. i get NULL value > > return > > by PyImport_Import() > > > > following is the code. code is copied from > > http://www.codeproject.com/cpp/embedpython_1.asp > > > > following file is saved as > > > > call_function.c > > > > > > > /************************************************************************************************************/ > > > > // call_function.c - A sample of calling > > // python functions from C code > > // > > #include > > > > int main(int argc, char *argv[]) > > { > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > > > if (argc < 3) > > { > > printf("Usage: exe_name python_source function_name\n"); > > return 1; > > } > > > > // Initialize the Python Interpreter > > Py_Initialize(); > > > > // Build the name object > > pName = PyString_FromString(argv[1]); > > > > // Load the module object > > pModule = PyImport_Import(pName); > > > > // pDict is a borrowed reference > > pDict = PyModule_GetDict(pModule); > > > > // pFunc is also a borrowed reference > > pFunc = PyDict_GetItemString(pDict, argv[2]); > > > > if (PyCallable_Check(pFunc)) > > { > > PyObject_CallObject(pFunc, NULL); > > } else > > { > > PyErr_Print(); > > } > > > > // Clean up > > Py_DECREF(pModule); > > Py_DECREF(pName); > > > > // Finish the Python Interpreter > > Py_Finalize(); > > > > return 0; > > } > > > > > > > /************************************************************************************************************/ > > python file saved as > > > > py_function.py > > > > > > > /************************************************************************************************************/ > > > > '''py_function.py - Python source designed to ''' > > '''demonstrate the use of python embedding''' > > > > def multiply(): > > c = 12345*6789 > > print 'The result of 12345 x 6789 :', c > > > > > > return c > > > > > > > /************************************************************************************************************/ > > > > $gcc -g call_function.c -lpython2.5 -ocall_function > > $./call_function py_function.py multiply > > > > i get following output > > > > ImportError: No module named py_function > > Failed to load "py_function" > > > > when i kdbg(debug) it i vet NULL value returned from PyImport_Import().. > > > > can any one please find out the error that i am doing. > > > > -- > > Shrikant > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > > http://mail.python.org/pipermail/c++-sig/attachments/20071025/e3ca2dfd/attachment-0001.htm > > > > ------------------------------ > > > > Message: 2 > > Date: Thu, 25 Oct 2007 08:21:19 +0100 > > From: "Gustavo Carneiro" > > Subject: Re: [C++-sig] failed in PyImport_Import() > > To: "Development of Python/C++ integration" > > Message-ID: > > > > Content-Type: text/plain; charset="utf-8" > > > > On 25/10/2007, Shrikant Chikhalkar wrote: > > > > > > Hi, > > > > > > i am tring to call python function from 'C' program. i get NULL value > > > return by PyImport_Import() > > > > > > following is the code. code is copied from > > > http://www.codeproject.com/cpp/embedpython_1.asp > > > > > > following file is saved as > > > > > > call_function.c > > > > > > > > > /************************************************************************************************************/ > > > > > > > > > // call_function.c - A sample of calling > > > // python functions from C code > > > > > > // > > > #include > > > > > > int main(int argc, char *argv[]) > > > { > > > > > > PyObject *pName, *pModule, *pDict, *pFunc, *pValue; > > > > > > if (argc < 3) > > > { > > > printf("Usage: exe_name python_source function_name\n" > > > ); > > > return 1; > > > } > > > > > > // Initialize the Python Interpreter > > > Py_Initialize(); > > > > > > > > > // Build the name object > > > pName = PyString_FromString(argv[1]); > > > > > > // Load the module object > > > pModule = PyImport_Import(pName); > > > > > > > > > // pDict is a borrowed reference > > > pDict = PyModule_GetDict(pModule); > > > > > > // pFunc is also a borrowed reference > > > pFunc = PyDict_GetItemString(pDict, argv[ > > > 2]); > > > > > > if (PyCallable_Check(pFunc)) > > > { > > > PyObject_CallObject(pFunc, NULL); > > > } else > > > { > > > > > > PyErr_Print(); > > > } > > > > > > // Clean up > > > Py_DECREF(pModule); > > > Py_DECREF(pName); > > > > > > // Finish the Python Interpreter > > > > > > Py_Finalize(); > > > > > > return 0; > > > } > > > > > > > > > /************************************************************************************************************/ > > > > > > python file saved as > > > > > > py_function.py > > > > > > > > > > > > /************************************************************************************************************/ > > > > > > '''py_function.py - Python source designed to ''' > > > '''demonstrate the use of python embedding''' > > > > > > def multiply(): > > > c = 12345*6789 > > > print 'The result of 12345 x 6789 :', c > > > > > > > > > > > > return c > > > > > > > > > > > > /************************************************************************************************************/ > > > > > > $gcc -g call_function.c -lpython2.5 -ocall_function > > > $./call_function py_function.py multiply > > > > > > Shouldn't this be: > > $./call_function py_function multiply > > > > I.e., you the module name should not have a .py extension. > > > > i get following output > > > > > > ImportError: No module named py_function > > > Failed to load "py_function" > > > > > > when i kdbg(debug) it i vet NULL value returned from > PyImport_Import().. > > > > > > can any one please find out the error that i am doing. > > > > > > -- > > > Shrikant > > > > > > > > > _______________________________________________ > > > 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: > > > http://mail.python.org/pipermail/c++-sig/attachments/20071025/0fc3b1ea/attachment-0001.htm > > > > ------------------------------ > > > > _______________________________________________ > > C++-sig mailing list > > C++-sig at python.org > > http://mail.python.org/mailman/listinfo/c++-sig > > > > > > End of C++-sig Digest, Vol 51, Issue 25 > > *************************************** > > > > > > -- > Shrikant Chikhalkar > +91 9850991554 > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/c++-sig/attachments/20071025/26af7201/attachment.htm > > ------------------------------ > > _______________________________________________ > C++-sig mailing list > C++-sig at python.org > http://mail.python.org/mailman/listinfo/c++-sig > > > End of C++-sig Digest, Vol 51, Issue 26 > *************************************** > -- Shrikant Chikhalkar +91 9850991554 -------------- next part -------------- An HTML attachment was scrubbed... URL: From roman.yakovenko at gmail.com Sun Oct 28 20:51:30 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Sun, 28 Oct 2007 21:51:30 +0200 Subject: [C++-sig] Wrapping out parameter for python access In-Reply-To: <51C471E6CBEC8148A08E065690F4DBDF016CCA1D@SHAEXC01.ent.sonic.com> References: <51C471E6CBEC8148A08E065690F4DBDF016CCA1D@SHAEXC01.ent.sonic.com> Message-ID: <7465b6170710281251l72fbcfc8sc65d5c6a613a1581@mail.gmail.com> On 10/22/07, Chang Chen wrote: > > Hi all > > This is a classical issue in boost python. I.e. removeing an argument > from the function definition and adding the "returned", by the original > function, value to the return statement of the function-wrapper > > For example : > > The original function is: > > inline void hello_world( std::string& hw ){ > hw = "hello world!"; > } > > And the wrapper is: > > inline std::string hello_world_wrapper() > { > std:string temp; > ::hello_world(temp); > Return temp; > } > > Py++ can help us to generate such wrapper, see > http://language-binding.net/pyplusplus/documentation/functions/transform > ation/built_in/output.html > > But in this thread > (http://mail.python.org/pipermail/c++-sig/2005-June/009097.html ), Dave > provided a start to write a wrapping template. > > In My case, only last parameter is out parameter and whether function > parameter count does not matter. The function signature looks like: > > Return function (T1 t1, T2 t2, TOUT& out); > > How to write a template for such function and integrate into def? > > Any suggestion? I attach the complete solution to the problem including build script and unittest. The key for solution is to use boost::bind library. P.S. anyone with good knowledge of MPL & PPL, and some free time :-), is welcome to improve the code -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: reducer.zip Type: application/zip Size: 1471 bytes Desc: not available URL: From dave at boost-consulting.com Tue Oct 30 00:31:12 2007 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 29 Oct 2007 19:31:12 -0400 Subject: [C++-sig] Comparing to None on the c++ side References: <3dc9bcf00710221056n4ca21944sea68faaa38960b1@mail.gmail.com> Message-ID: <87wst5a473.fsf@grogan.peloton> on Mon Oct 22 2007, "Matthew Scouten" wrote: > Right, so... > > Python just called a c++ function and passed an object of some sort. I > want to know if it happens to be a None, so I can take special > precautions to avoid disaster. > > I am trying to use something like: > > void foo(object o) > { > if( object() == o ) > { > //Make 3rdparty c++ lib call that prevents > //Sky from falling > } > else > { > //tell 3rdparty c++ lib to > //try to use o to prop up sky... > } > } > > This does not seem to be working like I expected (the sky falls anyway) > > So me question: > > is object() == o a valid and reliable way to test for None? I think so. You might add some "printfs" to help you figure out what's going on. Remember, you can use boost::python::eval. -- Dave Abrahams Boost Consulting http://www.boost-consulting.com From dave at boost-consulting.com Tue Oct 30 00:39:17 2007 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 29 Oct 2007 19:39:17 -0400 Subject: [C++-sig] stuffing a PyObject into a object References: <3dc9bcf00710190938h4e641d9bwb7118c20c1cb707f@mail.gmail.com> Message-ID: <87r6jda3tm.fsf@grogan.peloton> on Fri Oct 19 2007, "Matthew Scouten" wrote: > I can understand this except for a couple of things, > > What is the PyIter_Next there for? demonstration purposes? or is it an > essential part of the conversion? Same question for that whole second > line. I think it's a mistake. > will 'allow_null' make a 'None' out of a null pointer? or do some > other crazy thing? No, it makes a null handle. It seems superfluous, since the object ctor will throw an exception anyway if its argument is null. > more to the point, will this code work: > > object foo(void* callbackID == NULL) > { > boost::python::handle<> h(boost::python::allow_null((PyObject*)callbackID)) > return boost::python::object o(h); > } If the is not pre-incremented for you, then boost::python::handle<> h((PyObject*)callbackID)); return boost::python::object o(h); would be correct. Otherwise, you need boost::python::handle<> h(boost::python::borrowed((PyObject*)callbackID))); return boost::python::object o(h); > I am trying to understand what is going on, and not just fall into > guess and check programming. Good call. -- Dave Abrahams Boost Consulting http://www.boost-consulting.com From dave at boost-consulting.com Tue Oct 30 00:41:57 2007 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 29 Oct 2007 19:41:57 -0400 Subject: [C++-sig] How about class_<...>.enable_copy() ? References: <200706081706.37240.meine@informatik.uni-hamburg.de> <200707231922.15574.meine@informatik.uni-hamburg.de> <200707232257.05883.meine@informatik.uni-hamburg.de> <200710162237.08845.hans_meine@gmx.net> Message-ID: <87lk9la3p6.fsf@grogan.peloton> on Tue Oct 16 2007, Hans Meine wrote: > Hi again! > > Anyone cares to comment on my older posting? > > On Montag 23 Juli 2007, Hans Meine wrote: >> On Montag 23 Juli 2007, Hans Meine wrote: >> > foo = Foo(other) # copy constructor as in C++ (1) >> > foo = copy.copy(other) # pythonic copying (2) >> > foo = copy.deepcopy(other) # deepcopying (3) >> > >> > (1) is easy to do by exporting the copy constructor >> > >> > (2) could be implemented by setting __copy__ to the above copy >> > constructor, but one would assume __dict__ to be (non-deep)copied, too. >> > >> > (3) definitely needs its own implementation, which needs to call deepcopy >> > recursively. >> > >> > I would still believe that an .enable_copy() would be very handy. It >> > could possibly be controlled by an enum arg which of the above methods >> > should be exported. > > Here is the updated, perfectly working code for (2) and (3), which I propose > to be included in BPL. Also, some things appear hackish to me -- I would be > glad to get feedback on how to do this in a more "standard" way: Is there a reason to have a special interface for this? Suppose we just do it unconditionally unless the person wrapping passes noncopyable to class_<...> ? -- Dave Abrahams Boost Consulting http://www.boost-consulting.com From amohr at pixar.com Tue Oct 30 01:13:34 2007 From: amohr at pixar.com (Alex Mohr) Date: Mon, 29 Oct 2007 17:13:34 -0700 Subject: [C++-sig] How about class_<...>.enable_copy() ? In-Reply-To: <87lk9la3p6.fsf@grogan.peloton> References: <200706081706.37240.meine@informatik.uni-hamburg.de> <200707231922.15574.meine@informatik.uni-hamburg.de> <200707232257.05883.meine@informatik.uni-hamburg.de> <200710162237.08845.hans_meine@gmx.net> <87lk9la3p6.fsf@grogan.peloton> Message-ID: <4726772E.1060402@pixar.com> > Is there a reason to have a special interface for this? Suppose we > just do it unconditionally unless the person wrapping passes > noncopyable to class_<...> ? Speaking of which, is there any good reason why boost.python shouldn't correspondingly infer noncopyability if class_metadata<...>::wrapped derives from boost::noncopyable? Alex From rwgk at yahoo.com Tue Oct 30 01:35:31 2007 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Mon, 29 Oct 2007 17:35:31 -0700 (PDT) Subject: [C++-sig] stuffing a PyObject into a object Message-ID: <64255.35162.qm@web31106.mail.mud.yahoo.com> > > I can understand this except for a couple of things, > > > > What is the PyIter_Next there for? demonstration purposes? or is it an > > essential part of the conversion? Same question for that whole second > > line. > > I think it's a mistake. This is five years ago, but IIRC my reply was meant as food for thought. Why does it have to be a two-stage procedure with the detour through handle<>? My understanding was: it is meant to make you think about PyObject* = 0. > > will 'allow_null' make a 'None' out of a null pointer? or do some > > other crazy thing? > > No, it makes a null handle. It seems superfluous, since the object > ctor will throw an exception anyway if its argument is null. I wanted to give a realistic example why you may care about PyObject* = 0. We want to detect PyObject* = 0 without getting an exception (// end of iteration) *and* we don't want to have the bare PyObject* floating around since we may forget to decref later. > > I am trying to understand what is going on, and not just fall into > > guess and check programming. > > Good call. Guess and check is a fantastic way to find out what is going on (or as Germany's most famous poet, Goethe, put it: Probieren geht ueber studieren). Here is an example: void foo() { using namespace boost::python; PyObject* obj = 0; handle<> h(allow_null(obj)); std::cout << "HELLO" << std::endl << std::flush; } If you compile and run this function it will finish fine and show the HELLO. Without the allow_null() I get this: SystemError: NULL result without error in PyObject_Call and no HELLO. Ralf From hans_meine at gmx.net Tue Oct 30 08:19:02 2007 From: hans_meine at gmx.net (Hans Meine) Date: Tue, 30 Oct 2007 08:19:02 +0100 Subject: [C++-sig] How about class_<...>.enable_copy() ? In-Reply-To: <87lk9la3p6.fsf@grogan.peloton> References: <200706081706.37240.meine@informatik.uni-hamburg.de> <200710162237.08845.hans_meine@gmx.net> <87lk9la3p6.fsf@grogan.peloton> Message-ID: <200710300819.13004.hans_meine@gmx.net> On Dienstag 30 Oktober 2007, David Abrahams wrote: > > Here is the updated, perfectly working code for (2) and (3), which I > > propose to be included in BPL. Also, some things appear hackish to me -- > > I would be glad to get feedback on how to do this in a more "standard" > > way: > > Is there a reason to have a special interface for this? Suppose we > just do it unconditionally unless the person wrapping passes > noncopyable to class_<...> ? No; that would be even better (I originally thought about that, too). The only disadvantage I see is a bit more generated code, but I think that copying copyable objects is something that many users expect to be able to do. And for now, I really think that the possibility to disable it using noncopyable is enough; otherwise one might introduce an API for that later. -- Ciao, / / .o. /--/ ..o / / ANS ooo -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From bue.longbow at gmail.com Mon Oct 29 19:46:47 2007 From: bue.longbow at gmail.com (Bue Vedel-Larsen) Date: Mon, 29 Oct 2007 18:46:47 +0000 (UTC) Subject: [C++-sig] Inheritance and __init__ Message-ID: I'm having a strange problem with Boost::Python. Consider the following Python code: class Base: def foo(self, str): print str class Derived(Base): def __init__(self): self.foo('__init__') d = Derived() This works as expected: When run, "__init__" is printed. My problem is that if Base is in a C++ module the same code fails with an Boost.Python.ArgumentError. See end of post for example code that exhibit the error. Can anyone point out if I'm doing something wrong? I'm not using any virtual methods, or any kind of advanced inheritance magic. Is this a bug in Boost::Python? Thanks in advance, Bue The exact error is: Boost.Python.ArgumentError: Python argument types in Base.foo(DerivedB, str) did not match C++ signature: foo(class Base {lvalue}, class std::basic_string,class std::allocator >) Minimum example code: #include #include #include class Base { public: Base() {} ~Base() {} void foo( const std::string& str ) { std::cout << "In C++: " << str << std::endl; } }; BOOST_PYTHON_MODULE(test_module) { using namespace boost::python; (new class_< Base >( "Base", "Base class", init<>() )) ->def( "foo", &Base::foo, "method foo" ) ; } void run_script( const std::string& script ) { if( PyRun_SimpleString( script.c_str() ) ) { PyErr_Print(); PyErr_Clear(); } } int main() { PyImport_AppendInittab( "test_module", &inittest_module ); Py_Initialize(); run_script( "from test_module import *\n" ); // This works run_script( "class DerivedA(Base):\n" "\tdef bar(self):\n" "\t\tself.foo('In Python: DerivedA.bar()')\n" "dA = DerivedA()\n" "dA.bar()\n" ); // This doesn't work run_script( "class DerivedB(Base):\n" "\tdef __init__(self):\n" "\t\tself.foo('In Python: DerivedB.__init__()')\n" "dB = DerivedB()\n" ); #ifdef WIN32 system( "PAUSE" ); #endif return 0; } From hans_meine at gmx.net Tue Oct 30 11:37:32 2007 From: hans_meine at gmx.net (Hans Meine) Date: Tue, 30 Oct 2007 11:37:32 +0100 Subject: [C++-sig] Inheritance and __init__ In-Reply-To: References: Message-ID: <200710301137.42455.hans_meine@gmx.net> On Montag 29 Oktober 2007, Bue Vedel-Larsen wrote: > I'm having a strange problem with Boost::Python. Consider the following > Python code: > > class Base: > def foo(self, str): > print str > > class Derived(Base): > def __init__(self): You must call Base.__init__ here to initialize the base class. > self.foo('__init__') > > d = Derived() > > This works as expected: When run, "__init__" is printed. My problem is > that if Base is in a C++ module the same code fails with an > Boost.Python.ArgumentError. See end of post for example code that > exhibit the error. the BPL object is not initialized. -- Ciao, / / .o. /--/ ..o / / ANS ooo -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part. URL: From Mark.English at rbccm.com Tue Oct 30 11:38:30 2007 From: Mark.English at rbccm.com (English, Mark) Date: Tue, 30 Oct 2007 10:38:30 -0000 Subject: [C++-sig] Inheritance and __init__ References: Message-ID: > -----Original Message----- > From: c++-sig-bounces+mark.english=rbccm.com at python.org > [mailto:c++-sig-bounces+mark.english=rbccm.com at python.org] On > Behalf Of Bue Vedel-Larsen > Sent: 29 October 2007 18:47 > To: c++-sig at python.org > Subject: [C++-sig] Inheritance and __init__ > > I'm having a strange problem with Boost::Python. Consider the > following > Python code: > > class Base: > def foo(self, str): > print str > > class Derived(Base): > def __init__(self): > self.foo('__init__') > > d = Derived() > > This works as expected: When run, "__init__" is printed. My > problem is > that if Base is in a C++ module the same code fails with an > Boost.Python.ArgumentError. See end of post for example code that > exhibit the error. > > // This works > run_script( > "class DerivedA(Base):\n" > "\tdef bar(self):\n" > "\t\tself.foo('In Python: DerivedA.bar()')\n" > "dA = DerivedA()\n" > "dA.bar()\n" > ); > > // This doesn't work > run_script( > "class DerivedB(Base):\n" > "\tdef __init__(self):\n" > "\t\tself.foo('In Python: DerivedB.__init__()')\n" > "dB = DerivedB()\n" > ); Does it make a difference if in the __init__ methods you call "super(KlassName, self).__init__()" first ? E.g. "class DerivedB(Base):\n" "\tdef __init__(self):\n" "\t\tsuper(DerivedB, self).__init__() "\t\tself.foo('In Python: DerivedB.__init__()')\n" Cheers, mE ________________________________________ This E-Mail (including any attachments) may contain privileged or confidential information. It is intended only for the addressee(s) indicated above. The sender does not waive any of its rights, privileges or other protections respecting this information. Any distribution, copying or other use of this E-Mail or the information it contains, by other than an intended recipient, is not sanctioned and is prohibited. If you received this E-Mail in error, please delete it and advise the sender (by return E-Mail or otherwise) immediately. This E-Mail (including any attachments) has been scanned for viruses. It is believed to be free of any virus or other defect that might affect any computer system into which it is received and opened. However, it is the responsibility of the recipient to ensure that it is virus free. The sender accepts no responsibility for any loss or damage arising in any way from its use. E-Mail received by or sent from RBC Capital Markets is subject to review by Supervisory personnel. Such communications are retained and may be produced to regulatory authorities or others with legal rights to the information. IRS CIRCULAR 230 NOTICE: TO COMPLY WITH U.S. TREASURY REGULATIONS, WE ADVISE YOU THAT ANY U.S. FEDERAL TAX ADVISE INCLUDED IN THIS COMMUNICATION IS NOT INTENDED OR WRITTEN TO BE USED, AND CANNOT BE USED, TO AVOID ANY U.S. FEDERAL TAX PENALTIES OR TO PROMOTE, MARKET, OR RECOMMEND TO ANOTHER PARTY ANY TRANSACTION OR MATTER. From ndbecker2 at gmail.com Tue Oct 30 12:54:19 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 30 Oct 2007 07:54:19 -0400 Subject: [C++-sig] properties in python class that extend c++ base Message-ID: I have a c++ class with a property: class_ ("mod"... .add_property ("SPS", &mod_t::SPS) If I subclass this class in python: class X (mod): Then when python code attempts to access the property in the derived class, it fails: Boost.Python.ArgumentError: Python argument types in None.None(pi4_modulator) did not match C++ signature: None(modulator {lvalue}) Is there a solution to this? From nat at lindenlab.com Tue Oct 30 13:06:04 2007 From: nat at lindenlab.com (Nat Goodspeed) Date: Tue, 30 Oct 2007 08:06:04 -0400 Subject: [C++-sig] properties in python class that extend c++ base In-Reply-To: References: Message-ID: <47271E2C.4000803@lindenlab.com> Neal Becker wrote: > I have a c++ class with a property: > > If I subclass this class in python: > > class X (mod): > > Then when python code attempts to access the property in the derived class, > it fails: > Boost.Python.ArgumentError: Python argument types in > None.None(pi4_modulator) > did not match C++ signature: > None(modulator {lvalue}) Does the Python subclass __init__() call the base-class __init__()? From Mark.English at rbccm.com Tue Oct 30 13:16:18 2007 From: Mark.English at rbccm.com (English, Mark) Date: Tue, 30 Oct 2007 12:16:18 -0000 Subject: [C++-sig] properties in python class that extend c++ base References: Message-ID: > -----Original Message----- > From: c++-sig-bounces at python.org > [mailto:c++-sig-bounces at python.org] On Behalf Of Neal Becker > Sent: 30 October 2007 11:54 > To: c++-sig at python.org > Subject: [C++-sig] properties in python class that extend c++ base > > I have a c++ class with a property: > class_ ("mod"... > .add_property ("SPS", &mod_t::SPS) > > If I subclass this class in python: > > class X (mod): > > Then when python code attempts to access the property in the > derived class, it fails: > Boost.Python.ArgumentError: Python argument types in > None.None(pi4_modulator) > did not match C++ signature: > None(modulator {lvalue}) > > Is there a solution to this? If you overrode __init__ in the subclass, did you remember to call the Base class's __init__ ? What's the held type of the class_ ? ________________________________________ This E-Mail (including any attachments) may contain privileged or confidential information. It is intended only for the addressee(s) indicated above. The sender does not waive any of its rights, privileges or other protections respecting this information. Any distribution, copying or other use of this E-Mail or the information it contains, by other than an intended recipient, is not sanctioned and is prohibited. If you received this E-Mail in error, please delete it and advise the sender (by return E-Mail or otherwise) immediately. This E-Mail (including any attachments) has been scanned for viruses. It is believed to be free of any virus or other defect that might affect any computer system into which it is received and opened. However, it is the responsibility of the recipient to ensure that it is virus free. The sender accepts no responsibility for any loss or damage arising in any way from its use. E-Mail received by or sent from RBC Capital Markets is subject to review by Supervisory personnel. Such communications are retained and may be produced to regulatory authorities or others with legal rights to the information. IRS CIRCULAR 230 NOTICE: TO COMPLY WITH U.S. TREASURY REGULATIONS, WE ADVISE YOU THAT ANY U.S. FEDERAL TAX ADVISE INCLUDED IN THIS COMMUNICATION IS NOT INTENDED OR WRITTEN TO BE USED, AND CANNOT BE USED, TO AVOID ANY U.S. FEDERAL TAX PENALTIES OR TO PROMOTE, MARKET, OR RECOMMEND TO ANOTHER PARTY ANY TRANSACTION OR MATTER. From matthew.scouten at gmail.com Tue Oct 30 16:58:05 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Tue, 30 Oct 2007 10:58:05 -0500 Subject: [C++-sig] Am I crazy or is it my computer? Message-ID: <3dc9bcf00710300858j1de24addyfc9970340a76879d@mail.gmail.com> This is diving me nuts. I need to triple check an assumption. I am *extending* python using Boost::Python, by wrapping a complex c++ library that was written years ago with no thought of future use in python. The library works by a system of callouts and callbacks with extensive multithreading. There are a number of minor worker threads in the background, but [ASSUMPTION ONE:] this should not matter because they never need to use data or call code that is known to the interpretor. There is also a callback thread on which the callbacks are called. This is NOT a python thread, an interpretor thread, or ANY other special kind of thread. It was not started through the C/Python API. It is a system thread started through the WIN32 API in the byzantine depths of the library. It has not been introduced to the interpretor in any way. ASSUMPTION TWO: I can have that thread call into python code by using the PyGILState_Ensure & PyGILState_Release pair of functions as described in http://www.python.org/dev/peps/pep-0311/ and http://docs.python.org/api/threads.html to acquire the Global Interpretor Lock. (Actually: I am using Resource Acquisition Is Initialization idiom with the following simple class: class callback { public: inline callback() { state = PyGILState_Ensure(); } inline ~callback() { PyGILState_Release(state); } private: PyGILState_STATE state; }; This may be ASSUMPTION THREE) Are my assumptions valid? This may seem like a simple question that I should be googling for, but like I said I am triple checking some assumptions. I have been trying to debug the same extremely bizarre problem for a couple of days now and it only shows up in the asynchronous callbacks. From ndbecker2 at gmail.com Tue Oct 30 19:01:39 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 30 Oct 2007 14:01:39 -0400 Subject: [C++-sig] properties in python class that extend c++ base References: Message-ID: English, Mark wrote: >> -----Original Message----- >> From: c++-sig-bounces at python.org >> [mailto:c++-sig-bounces at python.org] On Behalf Of Neal Becker >> Sent: 30 October 2007 11:54 >> To: c++-sig at python.org >> Subject: [C++-sig] properties in python class that extend c++ base >> >> I have a c++ class with a property: >> class_ ("mod"... >> .add_property ("SPS", &mod_t::SPS) >> >> If I subclass this class in python: >> >> class X (mod): >> >> Then when python code attempts to access the property in the >> derived class, it fails: >> Boost.Python.ArgumentError: Python argument types in >> None.None(pi4_modulator) >> did not match C++ signature: >> None(modulator {lvalue}) >> >> Is there a solution to this? > If you overrode __init__ in the subclass, did you remember to call the > Base class's __init__ ? > What's the held type of the class_ ? Thanks guys. Yup, I had forgotten to call Base class __init__. From joel at boost-consulting.com Tue Oct 30 18:49:49 2007 From: joel at boost-consulting.com (Joel de Guzman) Date: Wed, 31 Oct 2007 01:49:49 +0800 Subject: [C++-sig] can't get Boost.Python tutorial's "Hello World" example to work (on linux) In-Reply-To: References: Message-ID: <47276EBD.5090007@boost-consulting.com> ted sandler wrote: > Hi all, > > I am running linux, and although the Boost.Python "Quickstart" example > works fine, I am not able to get the Boost.Python "Hello World" example > working. > > The quickstart example is located here > http://www.boost.org/libs/python/doc/building.html. > > The hello-world example is located here: > http://www.boost.org/libs/python/doc/tutorial/doc/html/python/hello.html. > > There are problems with the documentation on the hello-world web page > (I guess it's out of date). The example files in the Boost-distribution > are different from those described in the "hello-world" tutorial. > Specifically, the Boost distribution contains a "Jamroot" file while the > web page discusses both a "Jamfile" and a "Jamrules" file (whose > hyperlink is broken). > > Anyway, when I cd to the "hello-world" example directory and type bjam > at the prompt, bjam fails with the error message I've listed below. Any > help getting me up and running here would be great! Seems the tutorial is outdated indeed. I'll need to update the tutorial. In the meantime, see this thread: "Trouble with Boost.Python tutorial" where Dave suggests: "I suggest you work with http://www.boost.org/libs/python/doc/building.html until the tutorial gets fixed up." Regards, -- Joel de Guzman http://www.boost-consulting.com http://spirit.sf.net From bue.longbow at gmail.com Wed Oct 31 11:45:56 2007 From: bue.longbow at gmail.com (Bue Vedel-Larsen) Date: Wed, 31 Oct 2007 10:45:56 +0000 (UTC) Subject: [C++-sig] Inheritance and __init__ References: Message-ID: "English, Mark" wrote in news:EE7D40281B517A41AF5A90847A61F27937965615 at SEW39051.oak.fg.rbc.com: >> >> I'm having a strange problem with Boost::Python. Consider the >> following >> Python code: >> >> class Base: >> def foo(self, str): >> print str >> >> class Derived(Base): >> def __init__(self): >> self.foo('__init__') >> >> d = Derived() >> >> // This doesn't work >> run_script( >> "class DerivedB(Base):\n" >> "\tdef __init__(self):\n" >> "\t\tself.foo('In Python: DerivedB.__init__()')\n" >> "dB = DerivedB()\n" >> ); > Does it make a difference if in the __init__ methods you call > "super(KlassName, self).__init__()" first ? > E.g. > "class DerivedB(Base):\n" > "\tdef __init__(self):\n" > "\t\tsuper(DerivedB, self).__init__() > "\t\tself.foo('In Python: DerivedB.__init__()')\n" Amazing, adding "super(DerivedB, self).__init__()" or "Base.__init__ (self)" before self.foo('In Python: DerivedB.__init__()') makes it work. But why is this necessary? The pure Python example works without explicitly calling the __init__ method of the Base class. Do my class_ definition of the module lack something? Regards, Bue From Mark.English at rbccm.com Wed Oct 31 12:07:33 2007 From: Mark.English at rbccm.com (English, Mark) Date: Wed, 31 Oct 2007 11:07:33 -0000 Subject: [C++-sig] Inheritance and __init__ References: Message-ID: > -----Original Message----- > From: c++-sig-bounces at python.org > [mailto:c++-sig-bounces at python.org] On Behalf Of Bue Vedel-Larsen > Sent: 31 October 2007 10:46 > To: c++-sig at python.org > Subject: Re: [C++-sig] Inheritance and __init__ > > >> class Base: > >> def foo(self, str): > >> print str > >> > >> class Derived(Base): > >> def __init__(self): > >> self.foo('__init__') > >> > >> d = Derived() > >> > > >> // This doesn't work > >> run_script( > >> "class DerivedB(Base):\n" > >> "\tdef __init__(self):\n" > >> "\t\tself.foo('In Python: DerivedB.__init__()')\n" > >> "dB = DerivedB()\n" > >> ); > > Does it make a difference if in the __init__ methods you call > > "super(KlassName, self).__init__()" first ? > > E.g. > > "class DerivedB(Base):\n" > > "\tdef __init__(self):\n" > > "\t\tsuper(DerivedB, self).__init__() > > "\t\tself.foo('In Python: DerivedB.__init__()')\n" > > Amazing, adding "super(DerivedB, self).__init__()" or > "Base.__init__ (self)" before self.foo('In Python: > DerivedB.__init__()') makes it work. > > But why is this necessary? The pure Python example works > without explicitly calling the __init__ method of the Base > class. Do my class_ definition of the module lack something? > > Regards, > Bue As far as I know, the Python code working is undefined behaviour. Whenever overriding __init__() (especially for new style classes which Boost Python class_ instances implicitly are), call the base class __init__() passing through arguments as necessary. If you don't do this, the __init__ of the base class won't get called which for Boost Python is bad news. Try this: class Base(object): def __init__(self): super(Base, self).__init__() self.data = 1 class Derived(Base): def __init__(self): print 'I am derived' >>> d = Derived() #Happy I am derived >>> d.data #Unhappy Cheers, mE ________________________________________ This E-Mail (including any attachments) may contain privileged or confidential information. It is intended only for the addressee(s) indicated above. The sender does not waive any of its rights, privileges or other protections respecting this information. Any distribution, copying or other use of this E-Mail or the information it contains, by other than an intended recipient, is not sanctioned and is prohibited. If you received this E-Mail in error, please delete it and advise the sender (by return E-Mail or otherwise) immediately. This E-Mail (including any attachments) has been scanned for viruses. It is believed to be free of any virus or other defect that might affect any computer system into which it is received and opened. However, it is the responsibility of the recipient to ensure that it is virus free. The sender accepts no responsibility for any loss or damage arising in any way from its use. E-Mail received by or sent from RBC Capital Markets is subject to review by Supervisory personnel. Such communications are retained and may be produced to regulatory authorities or others with legal rights to the information. IRS CIRCULAR 230 NOTICE: TO COMPLY WITH U.S. TREASURY REGULATIONS, WE ADVISE YOU THAT ANY U.S. FEDERAL TAX ADVISE INCLUDED IN THIS COMMUNICATION IS NOT INTENDED OR WRITTEN TO BE USED, AND CANNOT BE USED, TO AVOID ANY U.S. FEDERAL TAX PENALTIES OR TO PROMOTE, MARKET, OR RECOMMEND TO ANOTHER PARTY ANY TRANSACTION OR MATTER. From neoguru at ioframe.com Wed Oct 31 13:30:09 2007 From: neoguru at ioframe.com (neoguru) Date: Wed, 31 Oct 2007 05:30:09 -0700 (PDT) Subject: [C++-sig] C++ singleton In-Reply-To: <0IOV00G2X0UGX6@cells-s02.cells.es> References: <0IOV00G2X0UGX6@cells-s02.cells.es> Message-ID: <13508067.post@talk.nabble.com> Yo may find usefull information about Singletin here: http://sourcemaking.com/design_patterns/singleton -- View this message in context: http://www.nabble.com/-C%2B%2B-sig--C%2B%2B-singleton-tf442256.html#a13508067 Sent from the Python - c++-sig mailing list archive at Nabble.com. From neoguru at ioframe.com Wed Oct 31 13:30:56 2007 From: neoguru at ioframe.com (neoguru) Date: Wed, 31 Oct 2007 05:30:56 -0700 (PDT) Subject: [C++-sig] C++ singleton In-Reply-To: <0IOV00G2X0UGX6@cells-s02.cells.es> References: <0IOV00G2X0UGX6@cells-s02.cells.es> Message-ID: <13508067.post@talk.nabble.com> Yo may find usefull information about Singleton here: http://sourcemaking.com/design_patterns/singleton -- View this message in context: http://www.nabble.com/-C%2B%2B-sig--C%2B%2B-singleton-tf442256.html#a13508067 Sent from the Python - c++-sig mailing list archive at Nabble.com. From bue.longbow at gmail.com Wed Oct 31 13:57:44 2007 From: bue.longbow at gmail.com (Bue Vedel-Larsen) Date: Wed, 31 Oct 2007 12:57:44 +0000 (UTC) Subject: [C++-sig] Inheritance and __init__ References: Message-ID: "English, Mark" wrote in news:EE7D40281B517A41AF5A90847A61F27947F8CE9E at SEW39051.oak.fg.rbc.com: >> But why is this necessary? The pure Python example works >> without explicitly calling the __init__ method of the Base >> class. Do my class_ definition of the module lack something? >> > As far as I know, the Python code working is undefined behaviour. > Whenever overriding __init__() (especially for new style classes which > Boost Python class_ instances implicitly are), call the base class > __init__() passing through arguments as necessary. > > If you don't do this, the __init__ of the base class won't get called > which for Boost Python is bad news. > Ah, ok. Thanks for clearing that up. Regards, Bue From matthew.scouten at gmail.com Wed Oct 31 21:11:27 2007 From: matthew.scouten at gmail.com (Matthew Scouten) Date: Wed, 31 Oct 2007 15:11:27 -0500 Subject: [C++-sig] Am I crazy or is it my computer? In-Reply-To: <3dc9bcf00710300858j1de24addyfc9970340a76879d@mail.gmail.com> References: <3dc9bcf00710300858j1de24addyfc9970340a76879d@mail.gmail.com> Message-ID: <3dc9bcf00710311311sb096aa1oc4b926b92f3aaaa8@mail.gmail.com> Ok, I just found this: http://www.boost.org/libs/python/doc/v2/faq.html#threadsupport I seems to be saying that I can not do what I want with out patching Boost::Python (or does this only apply to multiple interpretors? ) Is this still true (please tell me it's been fixed)? if so, where can I get this patch and how do I apply it? I asked about multi-threading and boost python in on this list a while ago, and got no answer. I took this a a "go ahead, no problems". If I am being an idiot, could you tell me so? Just flame away at me so I know I've been stupid. A lot of people here actually know what they are doing. I do not have that luxury. I am finding boost python extremely complex and non-intuitive. There is also a lack of good documentation (example code is nice to have, but does not constitute proper documentation all by itself). On 10/30/07, Matthew Scouten wrote: > This is diving me nuts. I need to triple check an assumption. > > I am *extending* python using Boost::Python, by wrapping a complex c++ > library that was written years ago with no thought of future use in > python. > > The library works by a system of callouts and callbacks with extensive > multithreading. > > There are a number of minor worker threads in the background, but > [ASSUMPTION ONE:] this should not matter because they never need to > use data or call code that is known to the interpretor. > > There is also a callback thread on which the callbacks are called. > This is NOT a python thread, an interpretor thread, or ANY other > special kind of thread. It was not started through the C/Python API. > It is a system thread started through the WIN32 API in the byzantine > depths of the library. It has not been introduced to the interpretor > in any way. > > ASSUMPTION TWO: > I can have that thread call into python code by using the > PyGILState_Ensure & PyGILState_Release pair of functions as described > in http://www.python.org/dev/peps/pep-0311/ and > http://docs.python.org/api/threads.html to acquire the Global > Interpretor Lock. > > (Actually: I am using Resource Acquisition Is Initialization idiom > with the following simple class: > > class callback > { > public: > inline callback() > { > state = PyGILState_Ensure(); > } > > inline ~callback() > { > PyGILState_Release(state); > } > > private: > PyGILState_STATE state; > }; > > This may be ASSUMPTION THREE) > > Are my assumptions valid? > > This may seem like a simple question that I should be googling for, > but like I said I am triple checking some assumptions. I have been > trying to debug the same extremely bizarre problem for a couple of > days now and it only shows up in the asynchronous callbacks. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rwgk at yahoo.com Wed Oct 31 23:41:09 2007 From: rwgk at yahoo.com (Ralf W. Grosse-Kunstleve) Date: Wed, 31 Oct 2007 15:41:09 -0700 (PDT) Subject: [C++-sig] Am I crazy or is it my computer? Message-ID: <642889.6428.qm@web31107.mail.mud.yahoo.com> I don't know too much about threading, but I think - you still need Niall Douglas' patches if your threads want to call back into Python - it is fair to say that the real problem is "Python & threading", mainly because of the dreaded global interpreter lock (GIL) Recently there has been some discussion on python-dev about getting rid of the GIL, but I'm not holding my breath... IIUC, if your threads never call back into Python you don't have to deal with the GIL. If you have to deal with the GIL I'm not surprised to see you frustrated. This is something that was largely ignored in the Boost.Python development (there is only so much you can hope to achieve in a given amount of time...). In my work I've consciously avoided threading. Under this simplification I find Boost.Python well documented and intuitive :-) Ralf ----- Original Message ---- From: Matthew Scouten To: Development of Python/C++ integration Sent: Wednesday, October 31, 2007 1:11:27 PM Subject: Re: [C++-sig] Am I crazy or is it my computer? Ok, I just found this: http://www.boost.org/libs/python/doc/v2/faq.html#threadsupport I seems to be saying that I can not do what I want with out patching Boost::Python (or does this only apply to multiple interpretors? ) Is this still true (please tell me it's been fixed)? if so, where can I get this patch and how do I apply it? I asked about multi-threading and boost python in on this list a while ago, and got no answer. I took this a a "go ahead, no problems". If I am being an idiot, could you tell me so? Just flame away at me so I know I've been stupid. A lot of people here actually know what they are doing. I do not have that luxury. I am finding boost python extremely complex and non-intuitive. There is also a lack of good documentation (example code is nice to have, but does not constitute proper documentation all by itself).