nagisa / rust_libloading

Bindings around the platform's dynamic library loading primitives with greatly improved memory safety.
https://docs.rs/libloading
ISC License
1.24k stars 102 forks source link

Using an sqlx database in a loaded async function #117

Closed ibx34 closed 1 year ago

ibx34 commented 1 year ago

I'm currently trying to make a plugin system for a project of mine and hit a road block. Loading the desired library works, and getting the function inside it works. However, when I try to call the function while passing in a database (pub struct Database(pub Pool<Postgres>) it fails.

Here is the function im trying to run:

#[no_mangle]
pub fn log_create(database: Arc<Database>, log: Messages) -> Pin<Box<dyn Future<Output = ()>>> {
    Box::pin(async move {
        if let Messages::CreateJobLog {
            job,
            status,
            step,
            output,
            pipe,
        } = log {
            sqlx::query::<_>(
                r#"INSERT INTO job_logs(job, step, status, output, pipe) VALUES($1,$2,$3,$4,$5)"#,
            )
            .bind(job)
            .bind(&step)
            .bind(status)
            .bind(&output)
            .bind(&pipe)
            .execute(&database.0)
            .await;
        };
    })
}

and here is what is invoking it:

let log_create_event: libloading::Symbol<unsafe extern "C" fn(Arc<Database>, Messages) -> Pin<Box<dyn Future<Output = ()>>>> = plugin.library.get(b"log_create").unwrap();

log_create_event(database.clone(), common::websocket::Messages::CreateJobLog {
    job,
    status,
    step: step.clone(),
    output: output.clone(),
    pipe: pipe.clone(),
  },
 )
 .await;
nagisa commented 1 year ago

Your function definition has no specified calling convention (which defaults to extern "Rust") while the loaded function specifies extern "C". This is most likely what's going wrong here. Some of https://doc.rust-lang.org/nomicon/ffi.html is probably quite useful to read through, as libloading is pretty much that, just that it happens at the runtime.

nagisa commented 1 year ago

I’ll close for now as answered but feel free to ask further questions.