Skip to content

Instantly share code, notes, and snippets.

@nebuta
Last active August 29, 2015 13:57
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 nebuta/9715400 to your computer and use it in GitHub Desktop.
Save nebuta/9715400 to your computer and use it in GitHub Desktop.
Rust FFI test with GSL
// gsltest.rs
//
// Rust version clone of the example of GSL linear algebra at
// http://www.gnu.org/software/gsl/manual/html_node/Linear-Algebra-Examples.html
//
// Works with Rust 0.9.
//
// Command for compiling on Mac OSX. You need to have GSL installed:
// rustc gsltest.rs -L/opt/local/lib
use std::libc::{c_int, size_t, c_double, c_char};
use std::vec::raw::buf_as_slice;
struct gsl_vector
{
size: size_t,
stride: size_t,
data: *c_double,
block: *gsl_block,
owner: c_int
}
struct gsl_vector_view {
vector: gsl_vector
}
struct gsl_matrix
{
size1: size_t,
size2: size_t,
tda: size_t,
data: *c_double,
block: *gsl_block,
owner: c_int
}
struct gsl_block {
size: size_t,
data: *c_double
}
struct gsl_matrix_view {
matrix: gsl_matrix
}
struct gsl_permutation {
size: size_t,
data: *size_t
}
#[link(name = "cblas")]
#[link(name = "gsl")]
extern {
fn gsl_vector_view_array(v: *c_double, n: size_t) -> gsl_vector_view;
fn gsl_vector_alloc(n: size_t) -> *gsl_vector;
fn gsl_vector_free(v: * gsl_vector) -> ();
fn gsl_matrix_view_array(vs: *c_double, row: size_t, col: size_t) -> gsl_matrix_view;
fn gsl_permutation_alloc(n: size_t) -> *gsl_permutation;
fn gsl_linalg_LU_decomp (A: * gsl_matrix, p: * gsl_permutation, signum: * int) -> c_int;
fn gsl_linalg_LU_solve(LU: *gsl_matrix, p: *gsl_permutation, b: *gsl_vector, x: * gsl_vector) -> c_int;
fn gsl_permutation_free(p: * gsl_permutation) -> ();
// I don't know yet how to use stdout for FFI.
//fn gsl_vector_fprintf (stream: * FILE, v: *gsl_vector, format: *c_char) -> c_int;
}
fn main() {
unsafe {
let arr: ~[c_double] = ~[0.18, 0.60, 0.57, 0.96,
0.41, 0.24, 0.99, 0.58,
0.14, 0.30, 0.97, 0.66,
0.51, 0.13, 0.19, 0.85];
let b_data: ~[c_double] = ~[1.0, 2.0, 3.0, 4.0];
let m: gsl_matrix_view = gsl_matrix_view_array(arr.as_ptr(),4,4);
let b: gsl_vector_view = gsl_vector_view_array(b_data.as_ptr(), 4);
let x: * gsl_vector = gsl_vector_alloc(4);
//println!("{:?}",(m.matrix.size1,m.matrix.size2));
let p: *gsl_permutation = gsl_permutation_alloc(4);
let mut s: int = 0;
gsl_linalg_LU_decomp(&m.matrix, p, &s);
gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x);
println("x = ");
let g = "%g".to_c_str();
buf_as_slice((*x).data, (*x).size as uint, |vs: &[c_double]| -> () {
for v in vs.iter() {
println!("{:?}",*v);
}
}
);
gsl_permutation_free(p);
gsl_vector_free(x);
println("Done");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment