# Ruby C++ extend, prb with free object

**URL:** <https://www.ruby-forum.com/t/ruby-c-extend-prb-with-free-object/130497>\
**Category:** Ruby\
**Created:** [February 28, 2008, 7:47pm UTC](https://www.ruby-forum.com/t/ruby-c-extend-prb-with-free-object/130497 "2008-02-28T19:47:11Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tonyryu](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e68b1a/32.png) [@tonyryu](https://www.ruby-forum.com/u/tonyryu)\
**Post date:** [February 28, 2008, 7:47pm UTC](https://www.ruby-forum.com/t/ruby-c-extend-prb-with-free-object/130497/1 "2008-02-28T19:47:11Z")

</div>

Sorry for my bad english.

I try to create an extention of interpreter ruby, with new class and  
module. But when i test my code, the object is never destruct before  
program’s ending. Maybe the garbage collector is disable or other, i  
don’t know.

My simple code C++ :

* * *

#include \<iostream.h\>  
#include “ruby.h”

// Class C++ Color  
class Color  
{  
private:  
int test;

public:  
Color();  
~Color();  
void proc\_test();  
void init();  
};

Color::Color()  
{  
std::cout \<\< “constructeur\n” ;  
}

Color::~Color()  
{  
std::cout \<\< “destructeur\n” ;  
}

void Color::proc\_test()  
{  
std::cout \<\< “test\n” ;  
}

void Color::init()  
{  
std::cout \<\< “init\n” ;  
}

/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/

static void rb\_color\_free( Color \*objColor )  
{  
std::cout \<\< “rb\_color\_free: enter\n”;  
delete objColor;  
std::cout \<\< “rb\_color\_free: leave\n”;  
}

static VALUE rb\_color\_new( VALUE self )  
{  
Color \*objColor = new Color();  
return Data\_Wrap\_Struct(self, 0, rb\_color\_free, objColor);  
}

static VALUE rb\_color\_init( VALUE self )  
{  
Color \*objColor;  
Data\_Get\_Struct(self, Color, objColor);  
objColor-\>init();  
return self;  
}

static VALUE rb\_color\_test(VALUE self)  
{  
Color \*objColor;  
Data\_Get\_Struct (self, Color, objColor);  
objColor-\>proc\_test();  
}

VALUE cColor;

void init\_color()  
{

```
cColor = rb_define_class( "Color", rb_cObject );

rb_define_alloc_func(cColor, rb_color_new);
rb_define_method( cColor, "initialize", (VALUE (*)(...)

```

)rb\_color\_init, 0 );  
rb\_define\_method( cColor, “essai”, (VALUE (\*)(…) )rb\_color\_test, 0  
);  
}

int main( int argc, char \*argv[] ) {

// Init ruby environment  
ruby\_init();  
ruby\_script(“embedded”);  
ruby\_init\_loadpath();

// Load my class Color definition  
init\_color();

rb\_load\_file(“test.rb”);  
ruby\_run();

## return 0; }

And the script ‘test.rb’ :

* * *

def test  
maCouleur = Color.new()  
maCouleur.essai  
end

## test() maCouleur = Color.new()

result :

* * *

## constructeur init test constructeur init rb\_color\_free: enter destructeur rb\_color\_free: leave rb\_color\_free: enter destructeur rb\_color\_free: leave

Why my class’s object are free at the end of program?
