Nim后端集成指南介绍了如何从C调用Nim函数。
示例功能:
proc fib(a: cint): cint {.exportc.} =
if a <= 2:
result = 1
else:
result = fib(a - 1) + fib(a - 2)
该过程要求指示Nim编译器不要创建main
函数,避免从以下位置链接和创建头文件到FFI:
$ nim c --noMain --noLinking --header:fib.h fib.nim
为了能够使用该函数,C主程序必须调用一个NimMain()
如下所示的函数:
#include "fib.h"
#include <stdio.h>
int main(void)
{
NimMain();
for (int f = 0; f < 10; f++)
printf("Fib of %d is %d\n", f, fib(f));
return 0;
}
前面提到的生成的头文件放置在nimcache
目录中。必须指示C编译器编译生成的nimcache
子目录下的所有文件,nimbase.h
并且main.c
:
$ gcc -o m -I$HOME/.cache/nim/fib_d -Ipath/to/nim/lib $HOME/.cache/nim/fib_d/*.c maths.c
我如何指示rust编译器在下面寻找那些翻译单元nimcache
?
在Rust项目中,可以具有构建脚本来编译和链接第三方非Rust代码。与cc
crate结合使用,可以更轻松地调用C / C ++编译器,这很有趣。
项目布局:
├── build.rs
├── Cargo.toml
└── src
├── fib.nim
└── main.rs
在build.rs
本身:
use std::io::{self, Write};
use std::process::Command;
fn main() {
let output = Command::new("nim")
.arg("c")
.arg("--noMain")
.arg("--noLinking")
.arg("--nimcache:nimcache")
.arg("src/fib.nim")
.output()
.expect("Failed to invoke nim compiler");
if !output.status.success() {
let msg = String::from_utf8_lossy(output.stderr.as_slice());
let _ = writeln!(io::stderr(), "\nerror occurred: {}\n", msg);
std::process::exit(1);
}
cc::Build::new()
.include("/usr/lib/nim")
.warnings(false)
.file("nimcache/fib.nim.c")
.file("nimcache/stdlib_system.nim.c")
.compile("fib_nim");
}
请注意,这里有几个与平台相关的位,主要是Nim标头位置。Nim编译器还被告知将中间文件放入nimcache
项目根目录下的目录中,而不是用户主目录下的默认目录中。
该Cargo.toml
文件中:
[package]
name = "nim-ffi"
version = "0.1.0"
authors = ["rustacean"]
edition = "2018"
[dependencies]
libc = "0.2"
[build-dependencies]
cc = "1.0"
最后是主要的Rust源文件:
use libc::c_int;
extern "C" {
fn NimMain();
fn fib(_: c_int) -> c_int;
}
fn main() {
// initialize nim gc memory, types and stack
unsafe {
NimMain();
}
let res = unsafe { fib(20) };
println!("Nim fib(20) is: {}", res);
}
它构建并成功运行:
$ cargo run
Nim fib(20) is: 6765
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句