Skip to content

Instantly share code, notes, and snippets.

@YakoYakoYokuYoku
Last active January 24, 2020 20:20
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 YakoYakoYokuYoku/9b92e35254edeeaab9180907fe082c3a to your computer and use it in GitHub Desktop.
Save YakoYakoYokuYoku/9b92e35254edeeaab9180907fe082c3a to your computer and use it in GitHub Desktop.
Call Rust from C#
// 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 }
// 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`
// 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