Created
March 22, 2012 17:02
-
-
Save crabtw/2159727 to your computer and use it in GitHub Desktop.
rust ffi
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
#include <stdio.h> | |
#include <netinet/in.h> | |
#include <sys/socket.h> | |
void ffunc(struct sockaddr_in s, struct sockaddr_in (*cb)(struct sockaddr_in)) { | |
printf("rust -> c\n"); | |
printf(" family: %u\n", s.sin_family); | |
printf(" port: %u\n", s.sin_port); | |
printf(" addr: %u\n", s.sin_addr.s_addr); | |
s.sin_family = AF_UNIX; | |
s.sin_port = 100; | |
s.sin_addr.s_addr = 200; | |
struct sockaddr_in t = cb(s); | |
printf("rust -> c\n"); | |
printf(" family: %u\n", t.sin_family); | |
printf(" port: %u\n", t.sin_port); | |
printf(" addr: %u\n", t.sin_addr.s_addr); | |
} | |
struct sockaddr_in mk_S() { | |
struct sockaddr_in s; | |
s.sin_family = AF_INET; | |
s.sin_port = 10; | |
s.sin_addr.s_addr = 20; | |
return s; | |
} |
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
gcc -c -fPIC -o ffunc.o ffunc.c | |
ar -r libffunc.a ffunc.o | |
~/src/rust-git/build/x86_64-unknown-linux-gnu/stage2/bin/rustc test.rs |
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
type S = { | |
mut sin_family: u16, | |
mut sin_port: u16, | |
mut sin_addr: u32, | |
mut sin_zero: (u8, u8, u8, u8, u8, u8, u8, u8) | |
}; | |
#[link_args="-L."] | |
native mod ffunc { | |
fn mk_S() -> S; | |
fn ffunc(++s: S, f: *u8); | |
} | |
crust fn cb(++s: S) -> S unsafe { | |
let x = s; | |
io::println("c -> rust"); | |
io::println(#fmt(" family: %u", x.sin_family as uint)); | |
io::println(#fmt(" port: %u", x.sin_port as uint)); | |
io::println(#fmt(" addr: %u", x.sin_addr as uint)); | |
x.sin_family = 7 as u16; | |
x.sin_port = 1000 as u16; | |
x.sin_addr = 2000 as u32; | |
ret x; | |
} | |
fn main(args: [str]) { | |
let s = ffunc::mk_S(); | |
io::println("c -> rust"); | |
io::println(#fmt(" family: %u", s.sin_family as uint)); | |
io::println(#fmt(" port: %u", s.sin_port as uint)); | |
io::println(#fmt(" addr: %u", s.sin_addr as uint)); | |
ffunc::ffunc(s, cb); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment