feat: add greet-rs
This commit is contained in:
Generated
+5
@@ -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"
|
||||
@@ -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]
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
gcc -Wall -shared greet.c -o libgreet.so
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user