# Saving Proc object in C extension

**URL:** <https://www.ruby-forum.com/t/saving-proc-object-in-c-extension/87285>\
**Category:** Ruby\
**Created:** [March 26, 2006, 4:42pm UTC](https://www.ruby-forum.com/t/saving-proc-object-in-c-extension/87285 "2006-03-26T16:42:51Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![victor123789](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/f0a364/32.png) [@victor123789](https://www.ruby-forum.com/u/victor123789)\
**Post date:** [March 26, 2006, 4:42pm UTC](https://www.ruby-forum.com/t/saving-proc-object-in-c-extension/87285/1 "2006-03-26T16:42:51Z")

</div>

Hi all.

The question is: can I save some Proc object in global variable of C  
extension?

What I’ve tried:

static VALUE g\_callback;

//some callback-saving function:  
static VALUE save\_callback(VALUE self, VALUE proc)  
{  
…bla-bla-bla…

rb\_global\_variable(&proc); //as recommended in “Extending Ruby”

g\_callback = proc;

…bla-bla-bla…  
}

But when I’ve tried to use the saved g\_callback later, I’ve received  
various  
errors. Moreover,

rb\_p(g\_callback);

prints some garbage or crashes (just like object g\_callback references  
is  
deleted). Raw integer value of g\_callback remains unchanged.

What I do wrong?

Thanks.

Victor.

---

<div class="post-metadata">

**Author:** ![victor123789](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/f0a364/32.png) [@victor123789](https://www.ruby-forum.com/u/victor123789)\
**Post date:** [March 26, 2006, 4:54pm UTC](https://www.ruby-forum.com/t/saving-proc-object-in-c-extension/87285/2 "2006-03-26T16:54:16Z")

</div>

> > > > > “V” == Victor S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) writes:

V\> static VALUE save\_callback(VALUE self, VALUE proc)  
V\> {  
V\> …bla-bla-bla…

V\> rb\_global\_variable(&proc); //as recommended in “Extending Ruby”

proc is on the stack, after the end of save\_callback() &proc don’t make  
reference to the proc object.

V\> What I do wrong?

This is g\_callback which must be registered.

static VALUE g\_callback;

static VALUE save\_callback(VALUE self, VALUE proc)  
{  
/\* … _/  
g\_callback = proc;  
/_ … \*/  
}

/\* … \*/

void Init\_bla\_bla\_bla()  
{  
/\* … _/  
g\_callback = Qnil;  
rb\_global\_variable(&g\_callback);  
/_ … \*/  
}

Guy Decoux

---

<div class="post-metadata">

**Author:** ![victor123789](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/f0a364/32.png) [@victor123789](https://www.ruby-forum.com/u/victor123789)\
**Post date:** [March 26, 2006, 5:04pm UTC](https://www.ruby-forum.com/t/saving-proc-object-in-c-extension/87285/3 "2006-03-26T17:04:57Z")

</div>

> V\> What I do wrong?
> 
> This is g\_callback which must be registered.

Thanks Guy! I’ve expected rb\_global\_variable uses only value of proc,  
not  
address. Now I’ve understand my error.

Thanks!

> Guy Decoux

Victor.
