简体   繁体   中英

Ruby inside C adding to $LOAD_PATH

Effectively I want to know if I can, purely through the use of Ruby's C library, append to $LOAD_PATH. The reason for doing so is that I have a written an extension (using Rice but that's not super important) and I would like for it to be self contained with a few others in their own directory.

Now, I already have two working solutions that I'm fine with. The first being that I simply use the Makefile generated by Rice to install the shared object automatically into a standard directory that is already on $LOAD_PATH. Super easy no hassle. The other is that I export $RUBY_LIB as the directory I want before running and the Ruby runtime picks up on that like a champ. But what I want to know is if I can do it only in C - for reference I am looking for functionality that mimics ruby -I./somedir

Right now I'm initialising Ruby in C the following way, this works fine with the previously mentioned working solutions but what I want is a way to cleanly add a directory to Ruby's $LOAD_PATH at runtime.

ruby_sysinit(&argc, &argv);
RUBY_INIT_STACK;
ruby_init();
ruby_init_loadpath();
....
rb_load_protect(...)
rb_funcall(...)

I could not figure out how to work with ruby_options , it just gave me a node and then blocked the main thread so I couldn't do anything; was I using it wrong?

Thanks!

To access the load the $LOAD_PATH variable, use the rb_gv_get("$LOAD_PATH") in your code.

The rb_gv_get("$LOAD_PATH") returns a Ruby array object, so any C array function can be used, such as rb_ary_unshift , rb_ary_push , etc.

For example:

VALUE load_path = rb_gv_get("$LOAD_PATH");
/* add a directory to Ruby's $LOAD_PATH */
rb_ary_push(load_path, rb_str_new2("any expanded directory"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM