Question

I have been through all the documents on Ruby C extensions that I can find to no good end.

Is there a complement to the Init_... method of initializing a C extension that is called as the interpreter exits?

Was it helpful?

Solution 2

There is no general "interpreter exiting" hook. But Ruby does garbage-collect everything on a normal exit, including Module and Class objects, and there is a way to hook object garbage collection. So you could adapt the following code that applies equally to Ruby interpreted objects or those defined by a C library:

module MyLib
end

ObjectSpace.define_finalizer( MyLib, proc { puts "MyLib unloaded" } )

You will need to take care to avoid assumptions that other Module or Class objects you expect to have available still exist when running this code, you are not in full control of the order in which this will get called on program exit.

OTHER TIPS

Ruby code can use Kernel#at_exit.

at_exit { puts "This code runs when Ruby exits." }

The implementation of Kernel#at_exit in eval_jump.c calls a C function, rb_set_end_proc(). This function is public, so you can call it from your own C code. The declaration is

void rb_set_end_proc(void (*)(VALUE), VALUE);

The first argument is a pointer to your C function (to get called when Ruby exits). The second argument is a Ruby value to pass to your C function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top