Last active
January 24, 2020 20:20
-
-
Save YakoYakoYokuYoku/9b92e35254edeeaab9180907fe082c3a to your computer and use it in GitHub Desktop.
Call Rust from C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Cargo.toml | |
[package] | |
name = "c-abi-to-rust" | |
version = "0.1.0" | |
authors = ["YakoYakoYokuYoku <gc1000ll@gmail.com>"] | |
edition = "2018" | |
[lib] | |
name = "ttaone" | |
crate-type = ["cdylib"] | |
[dependencies] | |
libc = { version = "0.2.66", default-features = false } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/lib.rs | |
extern crate libc; | |
use libc::c_double; | |
#[no_mangle] | |
extern "C" fn times_two_at_one(f: extern "C" fn(c_double) -> c_double) -> c_double { | |
2.0 * f(1.0) | |
} | |
// Compile with: | |
// `cargo build --release` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/main.cs | |
using System; | |
using System.Runtime.InteropServices; | |
public class Program | |
{ | |
[DllImport("ttaone", EntryPoint="times_two_at_one")] | |
public static extern double timesTwoAtOne(Func<double,double> f); | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine(timesTwoAtOne(Math.Tanh)); | |
} | |
} | |
// Compile with: | |
// `csc src/main.cs` | |
// Run in Linux/UNIX with: | |
// `LD_LIBRARY_PATH=target/release mono main.exe` | |
// Run in Windows with: | |
// `path %PATH%;target/release& mono main.exe` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment