Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

points example includes memory leak #5

Closed
plicease opened this issue Oct 30, 2015 · 4 comments
Closed

points example includes memory leak #5

plicease opened this issue Oct 30, 2015 · 4 comments

Comments

@plicease
Copy link
Member

re-write the points/line example so that it doesn't leak memory

@oylenshpeegul
Copy link

Do we just need to do this from_raw business?

#![crate_type = "dylib"]

// compile with: rustc points.rs
// borrowed with modifications from:
// http://paul.woolcock.us/posts/rust-perl-julia-ffi.html
// http://blog.skylight.io/bending-the-curve-writing-safe-fast-native-gems-with-rust/

pub struct Point {
    x: i32,
    y: i32,
}

struct Line {
    p1: Point,
    p2: Point,
}

impl Line {
    pub fn length(&self) -> f64 {
        let xdiff = self.p1.x - self.p2.x;
        let ydiff = self.p1.y - self.p2.y;

        ((xdiff.pow(2) + ydiff.pow(2)) as f64).sqrt()
    }
}

#[no_mangle]
pub extern "C" fn make_point(x: i32, y: i32) -> Box<Point> {
    let ptr = Box::into_raw(Box::new(Point { x: x, y: y }));
    unsafe { Box::from_raw(ptr) }
}

#[no_mangle]
pub extern "C" fn get_distance(p1: &Point, p2: &Point) -> f64 {
    Line {
        p1: Point { x: p1.x, y: p1.y },
        p2: Point { x: p2.x, y: p2.y },
    }
    .length()
}

@plicease
Copy link
Member Author

plicease commented Apr 8, 2019

@oylenshpeegul probably?

@plicease
Copy link
Member Author

@plicease
Copy link
Member Author

Thanks @oylenshpeegul that pointed me in the right direction!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants