feat: add greet-rs

This commit is contained in:
2020-10-01 00:03:03 +08:00
parent 9f605830d2
commit ce1b7dd4fb
8 changed files with 72 additions and 0 deletions

1
.gitignore vendored
View File

@@ -6,6 +6,7 @@ target/
wasm/pkg/
node_modules/
*.o
*.so
# These are backup files generated by rustfmt
**/*.rs.bk

5
live-reload-rust/greet-rs/Cargo.lock generated Normal file
View File

@@ -0,0 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "greet-rs"
version = "0.1.0"

View File

@@ -0,0 +1,9 @@
[package]
name = "greet-rs"
version = "0.1.0"
authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View File

@@ -0,0 +1,11 @@
build libgreet.so
direct build or use build.rs:
RUSTFLAGS="-L ${PWD}/.." cargo build
run:
LD_LIBRARY_PATH="${PWD}/.." ./target/debug/greet-rs

View File

@@ -0,0 +1,10 @@
use std::path::PathBuf;
fn main() {
let manifest_dir =
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("manifest dir should be set"));
let lib_dir = manifest_dir
.parent()
.expect("manifest dir should have a parent");
println!("cargo:rustc-link-search={}", lib_dir.display());
}

View File

@@ -0,0 +1,14 @@
use std::{ffi::CString, os::raw::c_char};
#[link(name = "greet")]
extern "C" {
fn greet(name: *const c_char);
}
fn main() {
let name = CString::new("fresh coffee").unwrap();
unsafe {
greet(name.as_ptr());
}
}

View File

@@ -0,0 +1 @@
gcc -Wall -shared greet.c -o libgreet.so

View File

@@ -0,0 +1,21 @@
#include <dlfcn.h>
#include <stdio.h>
typedef void (*greet_t)(const char *name);
int main(void) {
// this was `./libmain.so`
void *lib = dlopen("./libgreet.so", RTLD_LAZY);
if (!lib) {
fprintf(stderr, "failed to load library\n");
return 1;
}
greet_t greet = (greet_t) dlsym(lib, "greet");
if (!lib) {
fprintf(stderr, "could not look up symbol 'greet'\n");
return 1;
}
greet("venus");
dlclose(lib);
return 0;
}