easiest way to access rb_sprintf

A

Alex Fenton

Hi

I want to create a ruby method in a C++ extension that will spit out the
C++ pointer address of the wrapped object - useful for debugging. I
have got the following, which works, but I was wondering if there was an
easier way to access this that I'm missing?

static VALUE
cpp_ptr_addr(VALUE self, VALUE obj)
{
size_t ptr = (size_t)DATA_PTR(obj);
return rb_funcall( rb_mKernel, rb_intern("sprintf"), 2,
rb_str_new2("0x%x"), OFFT2NUM(ptr) );
}

thanks
alex
 
T

Tim Hunter

Alex said:
Hi

I want to create a ruby method in a C++ extension that will spit out the
C++ pointer address of the wrapped object - useful for debugging. I
have got the following, which works, but I was wondering if there was an
easier way to access this that I'm missing?

static VALUE
cpp_ptr_addr(VALUE self, VALUE obj)
{
size_t ptr = (size_t)DATA_PTR(obj);
return rb_funcall( rb_mKernel, rb_intern("sprintf"), 2,
rb_str_new2("0x%x"), OFFT2NUM(ptr) );
}

thanks
alex

Instead of calling Ruby's sprintf, use C's standard sprintf with the %p
conversion specifier, then convert the result to a Ruby string.
 
N

Nobuyoshi Nakada

Hi,

At Mon, 18 Aug 2008 22:31:41 +0900,
Alex Fenton wrote in [ruby-talk:311670]:
I want to create a ruby method in a C++ extension that will spit out the
C++ pointer address of the wrapped object - useful for debugging. I
have got the following, which works, but I was wondering if there was an
easier way to access this that I'm missing?

rb_sprintf is a function added in 1.9, and you can use it like
printf.
static VALUE
cpp_ptr_addr(VALUE self, VALUE obj)
{
void *ptr = DATA_PTR(obj);
return rb_sprintf("%p", ptr);
 
A

Alex Fenton

Nobuyoshi said:
void *ptr = DATA_PTR(obj);
return rb_sprintf("%p", ptr);

excellent, thank you both. i'm ultimately targetting 1.9 so this is ideal.

alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top