Note that there are some explanatory texts on larger screens.

plurals
  1. POpassing C++ classes instances to python with boost::python
    text
    copied!<p>I have a library which creates objects (instances of class A) and pass them to a python program which should be able to call their methods.</p> <p>Basically I have C++ class instances and I want to use them from python. Occasionally that object should be passed back to C++ for some manipulations.</p> <p>I created the following wrapper file (let's assume that the <code>New</code> function is called somewhere in the C++ code):</p> <pre><code>#include &lt;boost/python.hpp&gt; #include &lt;iostream&gt; #include &lt;boost/smart_ptr.hpp&gt; using namespace boost; using namespace boost::python; int calls = 0; struct A { int f() { return calls++; } ~A() { std::cout &lt;&lt; "destroyed\n"; } }; shared_ptr&lt;A&gt; existing_instance; void New() { existing_instance = shared_ptr&lt;A&gt;( new A() ); } int Count( shared_ptr&lt;A&gt; a ) { return a.use_count(); } BOOST_PYTHON_MODULE(libp) { class_&lt;A&gt;("A") .def("f", &amp;A::f) ; def("Count", &amp;Count); register_ptr_to_python&lt; shared_ptr&lt;A&gt; &gt;(); } </code></pre> <p>The code lacks the part where the python gets the <code>existing_instance</code>. I didn't paste that, but let's just say I use a callback mechanism for that purpose.</p> <p>This code works but I have a few questions:</p> <ol> <li><p>In the Count function (and in all other C++ manipulation functions) is it fine to pass <code>a</code> like that or it's better to do something like <code>const shared_ptr&lt;A&gt;&amp;</code>? In the code snippets I found in the python boost documentation the reference is often used but I don't understand the difference (apart from having a higher reference counter, of course).</p></li> <li><p>Is this code "safe"? When I pass the existing_instance to python, its counter will be incremented (just once, even if in python I make more copies of the object, of course) so there is no way that the C++ code could destroy the object as far as python holds at least a "copy". Am I correct? I tried to play with pointers and it seems I'm correct, I'm asking just to be sure.</p></li> <li><p>I'd like to prevent python from creating instances of A. They should only be passed from C++ code. How could I achieve that? <strong>EDIT</strong>: found, I just need to use no_init and noncopyable: <code>class_&lt;A, boost::noncopyable&gt;("A", no_init)</code></p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload