danielpclark / rutie

“The Tie Between Ruby and Rust.”
MIT License
940 stars 62 forks source link

Run On Exit: ruby_vm_at_exit #95

Closed frankwillis42 closed 5 years ago

frankwillis42 commented 5 years ago

I am reviewing rutie but I am unclear as to how I might be able to run a Rust function when the Ruby VM exits. There looks to be a Ruby C API called "ruby_vm_at_exit" which would serve this purpose, but I do not see this or anything similar in Rutie.

  1. Does Rutie have a preferred way to achieve this task? Or
  2. Is "ruby_vm_at_exit" exported and I simply need to reference it as an extern in my Rust code?

Thank you for any help you can provide!

danielpclark commented 5 years ago

You can run Ruby code at exit now by using a version of send to call Ruby's at_exit. If you want to write Rust code to be called you must define a method for Ruby in Rust that can be called in this way.

Ideally we'll eventually have #64 written to allow Rust code to be called more directly from Ruby and allowing things like Fibers to be implemented with Rust code as well.

The C signature for the command you asked about is:

void ruby_vm_at_exit(void(*func)(ruby_vm_t *));

And to implement it it may be as simple as a function pointer… or there may be more to implementing this required for the C type ruby_vm_t. I recommend going with the first suggestion here of writing a Ruby method in Rust to be called.

danielpclark commented 5 years ago

I'll tell you what. I'll try to take some time and implement this. Methods I plan to write for this:

The thing I said here

And to implement it it may be as simple as a function pointer… or there may be more to implementing this required for the C type ruby_vm_t.

turns out to be pretty simple… the C method expects a pointer to a C function and it will pass that function the current VM as the first parameter and I think it's a pointer to it. I'm not sure how we would use that or even if we would. Either way the function called on this method gets added to an array to be executed at exit.

danielpclark commented 5 years ago

I've added the feature you requested. You can find VM::at_exit at src/class/vm.rs.