Skip to content

Instantly share code, notes, and snippets.

@jonirrings
Last active March 26, 2021 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonirrings/75573b571d46151f072438b3d6fff062 to your computer and use it in GitHub Desktop.
Save jonirrings/75573b571d46151f072438b3d6fff062 to your computer and use it in GitHub Desktop.
rust libloading test

main.rs

use libloading;

fn call_dynamic() -> Result<u32, Box<dyn std::error::Error>> {
    unsafe {
        let lib = libloading::Library::new("/home/com/dev/cpp/libhello.so")?;
        let func: libloading::Symbol<unsafe extern "C" fn() -> u32> = lib.get(b"hello")?;
        Ok(func())
    }
}
fn main() {
    let x = call_dynamic();
    println!("{:?}", x);
}

hello.h

#ifndef hello_h__
#define hello_h__

#include <stdio.h>
#include <stdlib.h>

void hello();

#endif

hello.c

#include "hello.h"
void hello(){
    printf("hello from C \n");
}

compile to so

cd /home/com/dev/cpp
gcc -shared -fPIC hello.c -o libhello.so

cargo run

hello from C

Ok(14)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment