call rust from ruby

This commit is contained in:
Jaroslaw Konik 2025-05-09 18:42:37 +02:00
parent a4c5911603
commit b307cf6c13

View file

@ -79,10 +79,10 @@ impl Runtime for RubyRuntime {
type Value = RubyValue; type Value = RubyValue;
type RawEngine = (); type RawEngine = magnus::Ruby;
fn with_engine_mut<T>(&mut self, f: impl FnOnce(&mut Self::RawEngine) -> T) -> T { fn with_engine_mut<T>(&mut self, f: impl FnOnce(&mut Self::RawEngine) -> T) -> T {
todo!() f(&mut magnus::Ruby::get().unwrap())
} }
fn with_engine<T>(&self, f: impl FnOnce(&Self::RawEngine) -> T) -> T { fn with_engine<T>(&self, f: impl FnOnce(&Self::RawEngine) -> T) -> T {
@ -115,16 +115,22 @@ impl Runtime for RubyRuntime {
) -> Result<(), crate::ScriptingError> { ) -> Result<(), crate::ScriptingError> {
let ruby = magnus::Ruby::get().unwrap(); let ruby = magnus::Ruby::get().unwrap();
unsafe extern "C" fn callback(val: magnus::Value) -> magnus::Value { static mut FUN: Vec<Box<dyn Fn()>> = Vec::new();
unsafe {
FUN.push(Box::new(move || {
f((), vec![]).unwrap();
}));
}
fn callback() -> magnus::Value {
let ruby = magnus::Ruby::get().unwrap(); let ruby = magnus::Ruby::get().unwrap();
// f(); unsafe {
FUN.pop().unwrap()();
}
ruby.qnil().as_value() ruby.qnil().as_value()
} }
ruby.define_global_function( ruby.define_global_function(&name, function!(callback, 0));
&name,
callback as unsafe extern "C" fn(magnus::Value) -> magnus::Value,
);
Ok(()) Ok(())
} }
@ -155,25 +161,25 @@ pub mod prelude {
} }
impl<T> FromRuntimeValueWithEngine<'_, RubyRuntime> for T { impl<T> FromRuntimeValueWithEngine<'_, RubyRuntime> for T {
fn from_runtime_value_with_engine(value: RubyValue, engine: &()) -> Self { fn from_runtime_value_with_engine(value: RubyValue, engine: &magnus::Ruby) -> Self {
todo!(); todo!();
} }
} }
impl<T> IntoRuntimeValueWithEngine<'_, T, RubyRuntime> for T { impl<T> IntoRuntimeValueWithEngine<'_, T, RubyRuntime> for T {
fn into_runtime_value_with_engine(value: T, engine: &()) -> RubyValue { fn into_runtime_value_with_engine(value: T, engine: &magnus::Ruby) -> RubyValue {
todo!(); RubyValue(())
} }
} }
impl FuncArgs<'_, RubyValue, RubyRuntime> for () { impl FuncArgs<'_, RubyValue, RubyRuntime> for () {
fn parse(self, _engine: &()) -> Vec<RubyValue> { fn parse(self, _engine: &magnus::Ruby) -> Vec<RubyValue> {
Vec::new() Vec::new()
} }
} }
impl<T> FuncArgs<'_, RubyValue, RubyRuntime> for Vec<T> { impl<T> FuncArgs<'_, RubyValue, RubyRuntime> for Vec<T> {
fn parse(self, engine: &()) -> Vec<RubyValue> { fn parse(self, engine: &magnus::Ruby) -> Vec<RubyValue> {
self.into_iter().map(|x| RubyValue(())).collect() self.into_iter().map(|x| RubyValue(())).collect()
} }
} }
@ -183,7 +189,7 @@ macro_rules! impl_tuple {
impl<'a, $($t,)+> FuncArgs<'a, RubyValue, RubyRuntime> impl<'a, $($t,)+> FuncArgs<'a, RubyValue, RubyRuntime>
for ($($t,)+) for ($($t,)+)
{ {
fn parse(self, engine: &'a ()) -> Vec<RubyValue> { fn parse(self, engine: &'a magnus::Ruby) -> Vec<RubyValue> {
todo!(); todo!();
} }
} }