This commit is contained in:
Michael Zhang 2024-06-23 13:56:45 -05:00
parent acef87c56b
commit 947118def1
2 changed files with 45 additions and 14 deletions

View file

@ -1,24 +1,42 @@
use std::ffi::CString;
// Reference for FFI closures
// https://adventures.michaelfbryan.com/posts/rust-closures-in-ffi/
use sys::RegisterCallback;
use std::ffi::{c_char, c_void, CString};
pub mod sys {
use std::ffi::c_char;
use std::ffi::{c_char, c_void};
use crate::RegisterContext;
pub type RegisterCallback = fn(*mut RegisterContext) -> ();
use crate::RegisterCallback;
extern "C" {
pub fn register_endpoint(
url_len: u64,
url: *const c_char,
callback: *mut RegisterCallback,
callback_data: *mut c_void,
);
}
}
pub struct RegisterContext {}
pub type RegisterCallback = fn(*mut RegisterContext) -> ();
unsafe extern "C" fn register_endpoint_callback_trampoline<F>(
context: *mut RegisterContext,
register_callback: *mut c_void,
) where
F: FnMut(*mut RegisterContext),
{
let register_callback = &mut *(register_callback as *mut F);
register_callback(context);
}
pub fn get_trampoline<F>(_closure: &F) -> RegisterCallback
where
F: FnMut(*mut RegisterCallback),
{
register_endpoint_callback_trampoline::<F>
}
pub fn register_endpoint(
url: impl AsRef<str>,
@ -31,7 +49,8 @@ pub fn register_endpoint(
sys::register_endpoint(
url.len() as u64,
url_cstr.into_raw(),
&mut callback2 as *mut RegisterCallback,
register_endpoint_callback_trampoline,
&mut callback2 as *mut _ as *mut c_void,
)
};
println!("Result: {:?}", result);

View file

@ -3,13 +3,11 @@ use std::{
fs::{self, File},
io::Read,
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::{Context as _, Result};
use serde_yaml::Value;
use wasmtime::{
Caller, Config, Engine, Linker, Memory, MemoryType, Module, Store,
AsContext, Caller, Config, Engine, Linker, Memory, Module, Store,
};
use wasmtime_wasi::WasiCtxBuilder;
@ -115,10 +113,9 @@ impl AppState {
println!("WTF? {url_len} {url}");
let mem = caller.get_export("memory").and_then(|e| e.into_memory());
if let Some(mem) = mem {
let mut buffer = vec![0; url_len as usize];
mem.read(caller, url as usize, &mut buffer);
let string = String::from_utf8(buffer);
println!("{:?}", string);
let result =
read_utf_8string(&mut caller, &mem, url_len as usize, url as usize);
println!("{:?}", result);
}
// println!("my host state is: {}", caller.data());
},
@ -141,3 +138,18 @@ impl AppState {
Ok(())
}
}
fn read_utf_8string<C>(
c: C,
mem: &Memory,
len: usize,
offset: usize,
) -> Result<String>
where
C: AsContext,
{
let mut buffer = vec![0; len];
mem.read(c, offset, &mut buffer)?;
let string = String::from_utf8(buffer)?;
Ok(string)
}