Help with a C extension

E

Eric Merritt

Hello all,

I am slowly working through creating a C extension for ruby. There
are a couple of methods that would fit more correctly in existing
classes (specifically String and a few others). This is very easy to
do in Ruby, however, it I can't seem to find the way to go about it in
C. Any help would be appreciated.

Thanks
Eric
 
F

Friedrich Dominicus

Eric Merritt said:
Hello all,

I am slowly working through creating a C extension for ruby. There
are a couple of methods that would fit more correctly in existing
classes (specifically String and a few others). This is very easy to
do in Ruby, however, it I can't seem to find the way to go about it in
C. Any help would be appreciated.
I may missing something but what about
rb_define_method.

Get a handle to the String class and use rb_define_method

Regards
Friedrich
 
E

Eric Merritt

see inline ->

I may missing something but what about
rb_define_method.

no, no. lol. I get this.

Get a handle to the String class and use rb_define_method

Thats the question, how do you get a handle to an existing class. I
see plenty of documentation on how to create a class, but not how to
get a handle on an existing class.

-eric
 
K

Kristof Bastiaensen

Thats the question, how do you get a handle to an existing class. I
see plenty of documentation on how to create a class, but not how to get a
handle on an existing class.

The VALUE for String is rb_cString, and is defined in ruby.h.
If it wasn't there you could always get the class through Object:

rb_const_get(rb_cObject, rb_intern("String"));

Regards,
Kristof
 
E

Eric Merritt

Ah! thank you so much!


The VALUE for String is rb_cString, and is defined in ruby.h.
If it wasn't there you could always get the class through Object:

rb_const_get(rb_cObject, rb_intern("String"));

Regards,
Kristof
 
R

rcoder

You should be able to define extension methods for built-in classes the
same way you do for your own module.

For example:

VALUE my_extension_method(VALUE klass, VALUE self) {
/* do something here... */
return Qnil;
}

void Init_my_extension() {
rb_define_method(rb_cString, "my_method_name", my_extension_method,
0);
}
 
C

Charles Mills

This is helpful too:
VALUE rb_path2class _((const char*));

assert(rb_cString == rb_path2class("String"));
assert(rb_cArray == rb_path2class("Array"));
assert(cMyClass == rb_path2class("MyModule::MyClass"));

-Charlie
 

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
474,159
Messages
2,570,879
Members
47,417
Latest member
DarrenGaun

Latest Threads

Top