Repository: aisamanra/rust-haskell-ffi Branch: master Commit: e7114da60484 Files: 6 Total size: 5.5 KB Directory structure: gitextract_314mv98u/ ├── LICENSE ├── Makefile ├── README.md ├── fact.rs ├── main.hs └── point.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to ================================================ FILE: Makefile ================================================ RC = LD_LIBRARY_PATH=/usr/local/lib rustc GHC = ghc all: main libfact.a: fact.rs $(RC) --crate-type staticlib fact.rs libpoint.a: point.rs $(RC) --crate-type staticlib point.rs main: libfact.a libpoint.a main.hs $(GHC) main.hs libfact.a libpoint.a -lpthread -o main clean: rm -f libfact.a libpoint.a main.hi main.o main ================================================ FILE: README.md ================================================ # Rust-Haskell FFI Example A lot of Haskell people I've talked to are excited about the prospect of using Rust as a replacement for C in certain speed-critical or low-level parts of their application. To that end, and in light of the recent (as of this writing) Rust 1.0 alpha release, I've shown here a small example of calling Rust from Haskell. This contains a single Haskell file and two Rust libraries which Haskell can call out to. The first Rust library is contained in `fact.rs` and implements a simple factorial, which is easier to wrap; the second is contained in `point.rs` and demonstrates allocating memory in Rust, passing it to Haskell, using wrapped Rust functions to manipulate it, and finally allowing Haskell's GC to call back into Rust to free it. This of course requires GHC and a reasonably recent version of rustc installed. This version has been tested with GHC versions `7.8.4` and `7.10.1`, and the following rustc versions: 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) All the examples here I release into the public domain. ================================================ FILE: fact.rs ================================================ #![crate_type = "lib"] #[no_mangle] pub extern fn fact(x: u64) -> u64 { match x { 0 => 1, _ => x * fact(x-1), } } ================================================ FILE: main.hs ================================================ {-# LANGUAGE ForeignFunctionInterface #-} import Foreign import Foreign.C.Types import Foreign.ForeignPtr -- Wrapping the fact.rs module... foreign import ccall "fact" c_fact :: CULong -> CULong fact :: Int -> Int fact = fromIntegral . c_fact . fromIntegral -- A little bit more work to wrap the point.rs module; I also -- don't bother to write a proper representation for the -- underlying Point, which ought to be an instance of Storable -- if we want to manipulate it in Rust-land or do pointer -- arithmetic. type Point = ForeignPtr PointRepr data PointRepr foreign import ccall safe "mk_point" mk_point :: CULong -> CULong -> IO (Ptr PointRepr) foreign import ccall safe "add_point" add_point :: Ptr PointRepr -> Ptr PointRepr -> IO () foreign import ccall safe "print_point" print_point :: Ptr PointRepr -> IO () foreign import ccall safe "&free_point" free_point :: FunPtr (Ptr PointRepr -> IO ()) -- We use the free_point function as a finalizer when we -- create a point; this lets the Haskell GC take over for -- us. mkPoint :: Int -> Int -> IO Point mkPoint x y = do ptr <- mk_point (fromIntegral x) (fromIntegral y) newForeignPtr free_point ptr -- This modifies the first point in-place. addPoint :: Point -> Point -> IO () addPoint x y = withForeignPtr x (\ x' -> withForeignPtr y (\ y' -> add_point x' y')) -- This prints its argument printPoint :: Point -> IO () printPoint p = withForeignPtr p print_point -- Testing the point functions; we don't need to free -- explicitly because GHC should call our finalizer points :: IO () points = do a <- mkPoint 2 3 b <- mkPoint 1 1 addPoint a b printPoint a -- And here we go! main :: IO () main = do putStr "fact(5) = " print (fact 5) points ================================================ FILE: point.rs ================================================ #![crate_type = "lib"] // We aren't exposing the internals of this, so I don't bother giving it // a C representation. pub struct Point { x: u64, y: u64, } // Rust-land functions... impl Point { fn new(x: u64, y: u64) -> Point { Point { x: x, y: y } } fn add_mut(&mut self, p: &Point) { self.x = self.x + p.x; self.y = self.y + p.y; } } // What we're doing here is a little bit unsafe---by exposing // these elsewhere, we effectively transfer the 'ownership' out // of Rust-land. In this case, we'll have a corresponding free // function which takes ownership back again. #[no_mangle] pub extern fn mk_point(x: u64, y: u64) -> Box { Box::new(Point::new(x, y)) } // We free something in Rust by… taking ownership of it and doing nothing. #[no_mangle] pub extern fn free_point(_: Box) {} // Wrap our add_mut method for exporting. #[no_mangle] pub extern fn add_point(p1: &mut Point, p2: &Point) { p1.add_mut(p2); } // Wrap our print method for exporting. #[no_mangle] pub extern fn print_point(p: &Point) { println!("Point(x={}, y={})", p.x, p.y); }