From f09149f4f7fee8fb956afeed6b8d9dfb68ab7073 Mon Sep 17 00:00:00 2001 From: Andrey Voronkov Date: Fri, 16 Aug 2019 22:06:19 +0200 Subject: [PATCH] Add rust to go dynamic library example. --- rust-to-go-dynamic/Cargo.toml | 10 ++++++++++ rust-to-go-dynamic/build.rs | 13 +++++++++++++ rust-to-go-dynamic/src/double.go | 10 ++++++++++ rust-to-go-dynamic/src/main.rs | 12 ++++++++++++ 4 files changed, 45 insertions(+) create mode 100644 rust-to-go-dynamic/Cargo.toml create mode 100644 rust-to-go-dynamic/build.rs create mode 100644 rust-to-go-dynamic/src/double.go create mode 100644 rust-to-go-dynamic/src/main.rs diff --git a/rust-to-go-dynamic/Cargo.toml b/rust-to-go-dynamic/Cargo.toml new file mode 100644 index 0000000..3e98c02 --- /dev/null +++ b/rust-to-go-dynamic/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "rust-to-go" +version = "0.1.0" +authors = ["Andrey Voronkov "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +libc = "0.2" diff --git a/rust-to-go-dynamic/build.rs b/rust-to-go-dynamic/build.rs new file mode 100644 index 0000000..03936ef --- /dev/null +++ b/rust-to-go-dynamic/build.rs @@ -0,0 +1,13 @@ +use std::process::Command; + +fn main() { + println!(r"cargo:rustc-link-search=target/debug"); + let os = Command::new("uname") + .output().unwrap(); + let ext = match String::from_utf8_lossy(os.stdout.as_slice()).into_owned().trim_end().as_ref() { + "Darwin" => "dylib", + _ => "so" + }; + Command::new("go").args(&["build", "-o", &format!("target/debug/libdouble_input.{}", ext), "-buildmode=c-shared", "src/double.go"]) + .status().unwrap(); +} diff --git a/rust-to-go-dynamic/src/double.go b/rust-to-go-dynamic/src/double.go new file mode 100644 index 0000000..f877928 --- /dev/null +++ b/rust-to-go-dynamic/src/double.go @@ -0,0 +1,10 @@ +package main + +import "C" + +//export DoubleInput +func DoubleInput(input int32) int32 { + return input * 2 +} + +func main() {} diff --git a/rust-to-go-dynamic/src/main.rs b/rust-to-go-dynamic/src/main.rs new file mode 100644 index 0000000..99fb7d8 --- /dev/null +++ b/rust-to-go-dynamic/src/main.rs @@ -0,0 +1,12 @@ +extern crate libc; + +#[link(name = "double_input")] +extern { + fn DoubleInput(input: libc::c_int) -> libc::c_int; +} + +fn main() { + let input = 2; + let output = unsafe { DoubleInput(input) }; + println!("{} * 2 = {}", input, output); +}