4

I'm trying to implement a malloc type function, but I can't figure out what to use instead of the sbrk function found in unistd.h for C. Is there any way to FFI unistd.h into a Rust program?

Harvey Adcock
  • 929
  • 1
  • 7
  • 16

1 Answers1

3

The Rust Programming Language book as some good info on FFI. If you use libc, and cargo you could use something like the following.

extern crate libc;

use libc;

extern {
    fn sbrk(x: usize) -> *mut libc::c_void;
}

fn call_sbrk(x: usize) -> *mut libc::c_void {
    unsafe {
        sbrk(x)
    }
}

fn main() {
    let x = call_sbrk(42);
    println!("{:p}", x);
}

with something like the following in your Cargo.toml

[dependencies]
libc = "^0.2.7"
Daniel Robertson
  • 1,354
  • 13
  • 22
  • 2
    Nota bene: [one should shy away from using `pkg = "*"`](http://doc.crates.io/faq.html#can-libraries-use--as-a-version-for-their-dependencies) – набиячлэвэли Feb 23 '16 at 20:09
  • Thanks for catching my laziness! The post has been edited. – Daniel Robertson Feb 23 '16 at 21:28
  • Cheers, that's perfect - I was close but thought I needed some `#[link(name = "")]` thing in there, and couldn't figure out what to put as the name. – Harvey Adcock Feb 25 '16 at 00:24
  • 1
    If you're writing an allocator, you may also be interested in this chapter on Rust [Custom Allocators](https://doc.rust-lang.org/book/custom-allocators.html) – Daniel Robertson Feb 25 '16 at 13:37
  • @DanielRobertson That looks like an interesting chapter, I'll have to give it a god once I've sorted my allocator out. I'm now having some trouble with global variables and FFI - I've followed the chapter on it, but the linker is saying they're undefined but the names have had an underscore put before them. e.g. `PROT_WRITE` is showing as `_PROT_WRITE`. Any ideas? – Harvey Adcock Feb 25 '16 at 14:50
  • Just realised they aren't global variables, they're macro defined constants, which FFI can't handle. – Harvey Adcock Feb 25 '16 at 15:09