Merge pull request #27 from Itanq/master

Add dart to rust example
This commit is contained in:
Alex Crichton
2019-06-05 09:00:51 -05:00
committed by GitHub
4 changed files with 43 additions and 0 deletions

8
dart-to-rust/Cargo.toml Normal file
View File

@@ -0,0 +1,8 @@
[package]
name = "dart-to-rust"
version = "0.1.0"
authors = ["Zmant <zmant724@aliyun.com"]
[lib]
name = "rust_add"
crate-type = ["cdylib"]

18
dart-to-rust/Makefile Normal file
View File

@@ -0,0 +1,18 @@
ifeq ($(shell uname),Darwin)
LDFLAGS := -Wl,-dead_strip
else
LDFLAGS := -Wl,--gc-sections -lpthread -ldl
endif
all: target/debug/librust_add.so
dart src/main.dart
target/debug/librust_add.so: src/lib.rs Cargo.toml
cargo build
target/main.o: src/main.c | target
$(CC) -o $@ -c $<
clean:
rm -rf target
rm -rf Cargo.lock

5
dart-to-rust/src/lib.rs Normal file
View File

@@ -0,0 +1,5 @@
#[no_mangle]
pub extern fn rust_add(a: i32, b: i32) -> i32 {
a + b
}

View File

@@ -0,0 +1,12 @@
import 'dart:ffi' as ffi;
typedef NativeRustAddFunction = ffi.Int32 Function(ffi.Int32, ffi.Int32);
typedef NativeAddFunction = int Function(int, int);
main() {
ffi.DynamicLibrary dl = ffi.DynamicLibrary.open("target/debug/librust_add.so");
var add = dl.lookupFunction<NativeRustAddFunction, NativeAddFunction>("rust_add");
var number = add(12,13);
print("call rust function add(12,13)=$number");
}