Boost logo

Boost :

From: Phlip (pplumlee_at_[hidden])
Date: 2001-02-09 18:00:34


Boosters

Okay ya bunch'a 'leet script kiddies I got it. Below my sig is a New
Improved "example1.cpp", which I recommend y'all make the official
version to cut down on list server noise like this.

Here's the python code to test it:

    n = world(1)
    m = n.getWorld(1)
    assert (m != None)
    m = n.getWorld(0)
    assert (m == None)

The secret was we can't call 'to_python' >above< the instantiation of the
'class_builder<hello::world>' class, because 'to_python' has to be able to
see its traits.

Thanks for the help; BPL looks like a lock on our project.

-- 
  Phlip                          phlip_cpp_at_[hidden]
============ http://c2.com/cgi/wiki?PhlIp ============
  --  All sensors report Patti having a very good time  --
#include <string.h>
#include <boost/python/class_builder.hpp>
#include <boost/python/conversions.hpp>
using namespace boost; // don't do this
typedef python::ref reference_t;
namespace hello {
  class world
  {
   public:
      world(int) {}
      ~world() {}
      const char* get() const { return "hi, world"; }
	typedef shared_ptr<world> world_ptr_t;
	reference_t getWorld(int x);
  };
  size_t length(const world& x) { return strlen(x.get()); }
}
// Python requires an exported function called init<module-name> in every
// extension module. This is where we build the module contents.
extern "C"
#ifdef _WIN32
__declspec(dllexport)
#endif
void inithello()
{
    try
    {
       // create an object representing this extension module
       boost::python::module_builder hello("hello");
       // Create the Python type object for our extension class
       boost::python::class_builder<hello::world> world_class(hello, 
"world");
       // Add the __init__ function
       world_class.def(boost::python::constructor<int>());
       // Add a regular member function
       world_class.def(&hello::world::get, "get");
       world_class.def(&hello::world::getWorld, "getWorld");
       // Add a regular function to the module
       hello.def(hello::length, "length");
    }
    catch(...)
    {
       boost::python::handle_exception();    // Deal with the exception 
for Python
    }
}
 // this is below class_builder so to_python sees it
	reference_t 
hello::world::getWorld(int x) {
		if (x)
			{
			world_ptr_t p (new world (x));
			return to_python (p);
			}
		else
			{
			Py_INCREF(Py_None);
			return Py_None;
			}
		}
// Win32 DLL boilerplate
#if defined(_WIN32)
#include <windows.h>
extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID)
{
    return 1;
}
#endif // _WIN32

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk