Forums | Admin

Discussion Forums: help

Start New Thread Start New Thread

 

By: Matt Amos
How best to wrap boost::shared_ptr [ reply ]  
2008-04-02 22:31
I'm trying to wrap a couple of functions which either return or take as arguments boost shared pointers, but I seem to have done something wrong. Could anyone help me?

Here is the example I've been working with.

#include "rice/Class.hpp"
#include "rice/Data_Type.hpp"
#include "rice/Constructor.hpp"
#include <boost/shared_ptr.hpp>
#include <iostream>

using namespace Rice;

class Foo {
std::string name_;

public:

Foo(const std::string &n)
: name_(n) {
std::cerr << "Constructing with name " << name_ << "\n";
}

~Foo() {
std::cerr << "Destructing with name " << name_ << "\n";
}

std::string name() const {
return name_;
}
};

typedef boost::shared_ptr<Foo> foo_ptr;

foo_ptr
foo_create(Object self) {
Foo *foo = new Foo("blah");
return foo_ptr(foo);
}

std::string
foo_assign(Object self, foo_ptr &ptr) {
return ptr->name();
}

static Data_Type<Foo> rb_cFoo;

template<>
Object to_ruby<foo_ptr>(foo_ptr const &f) {
return Data_Wrap_Struct(rb_cFoo, 0,
Default_Allocation_Strategy<foo_ptr*>::free,
new foo_ptr(f));
}

extern "C"
void Init_test() {
Module rb_mTest = define_module("Test")
.define_singleton_method("create", &foo_create)
.define_singleton_method("assign", &foo_assign);

rb_cFoo = define_class_under<Foo>(rb_mTest, "Foo")
.define_constructor(Constructor<Foo,std::string>())
.define_method("to_s", &Foo::name);
}