Live data from Hacker News

Rust for C++ programmers – part 4: unique pointers

featherweightmusings.blogspot.com

51–60 of 99 posts

Re: Rust for C++ programmers – part 4: unique pointers

#51

I recently wondered whether it's possible to compile rust into a dll/so or whether there is a way to call rust from other languages (e.g. C, R, or ruby). All I found is that this isn't (easily?) possible because of rust's runtime. Is this true? If so, will it be possible to call rust from, e.g., C code? I'd like to have an alternative to c/c++ for writing native extensions for interpreted languages.

> If so, will it be possible to call rust from, e.g., C code? I'd like to have an alternative to c/c++ for writing native extensions for interpreted languages.

Yes. Technically it's already possible[0][1] but AFAIK it requires throwing out all (?) of the stdlib. rust-core[2] is an exploration of a runtime-less subset of the stdlib, which would ultimately be usable under a no_rt flag or something like that (at this point you have to disable the stdlib entirely and use rust-core instead)

[0] https://github.com/mozilla/rust/issues/3608

[1] https://github.com/charliesome/rustboot

[2] https://github.com/thestinger/rust-core

Re: Rust for C++ programmers – part 4: unique pointers

#52
post #45

From the blog: > I have history with Firefox layout and graphics, and programming language theory and type systems (mostly of the OO, Featherweight flavour, thus the title of the blog). Hmm, what are "type systems" of "featherweight flavour"? Anything real or some inside joke? Or perhaps an elaborate way to say "not that complicated"? (Google mostly returns references to the same blog)

Featherweight Java (http://www.fos.kuis.kyoto-u.ac.jp/~igarashi/papers/fj.html) was a seminal paper which showed type soundness for Java. The formal syntax was a subset of Java subset and preserved the interesting features in the semantics (as opposed to encoding a language in an extension of the lambda calculus, which is an alternative style of formalisation). So, "featherweight flavour" refers to formal type systems work which follows this style of formalisation.

Re: Rust for C++ programmers – part 4: unique pointers

#53

I recently wondered whether it's possible to compile rust into a dll/so or whether there is a way to call rust from other languages (e.g. C, R, or ruby). All I found is that this isn't (easily?) possible because of rust's runtime. Is this true? If so, will it be possible to call rust from, e.g., C code? I'd like to have an alternative to c/c++ for writing native extensions for interpreted languages.

Yes, it is possible to do it by just avoiding the runtime, e.g. the following works fine:

    #![crate_id="example_c"]
    #![crate_type="dylib"]
    
    #[no_mangle]
    pub extern fn my_rust_function(x: i32, y: i32) -> i32 {
        x + y
    }
Then compiling that gives a libexample_c....so file, which can be linked against the following C:

    #include
    extern int my_rust_function(int, int);

    int main() {
        printf("%d", my_rust_function(1, 2));
        return 0;
    }
printing 3. (There's no interaction with a runtime here at all.)

In fact, it's even possible to "manually" start a runtime[1] inside another process (and if it's started on its own thread then I think it will work flawlessly, if not, then it might break in some corner cases).

[1]: http://static.rust-lang.org/doc/master/guide-runtime.html

Re: Rust for C++ programmers – part 4: unique pointers

#54

I've been working C++ professionally for a couple of years and honestly I'm a huge fan - So I was excited to read about an alternative. After reading your 5 posts, I get the impression that RUST is mostly mildly useful syntactic sugar on top of C++. Here is my feedback: 1 - If memory management is a serious problem for the software you work on, I've never found the boost library lacking. This seems like the main sell…

> If memory management is a serious problem for the software you work on, I've never found the boost library lacking. As a developer that isn't working with C++, I'm finding memory management in C++ to be a nightmare and no amount of libraries can solve it. Say you receive a pointer from somewhere. Is the referenced value allocated on the stack or on the heap? If allocated on the heap, do you need to free it yourself…

> Say you receive a pointer from somewhere.

Here's your problem. In general I don't want to be receiving a single pointer from anyone. Lately, I've found it helpful to think of pointers in C++ as special iterators rather than a referential relic from C. In such a mindset passing pointers around without an accompanying end iterator, or iteration count, just makes no sense. Anywhere that implied iteration count is always a constant, I'm probably not structuring my code correctly.

So my recommendation is to use references (foo&) for passing down (well, up) the stack, never to heap allocated objects. Because you can't use delete on a reference there's no longer an ambiguity. Use smart pointers to manage the heap. Write RAII wrappers (it's not a lot of code) to manage external resources. RAII wrappers are especially useful for encapsulating smart pointers so big things can be passed around with value semantics, which gives you even stronger ability to reason. Implementing optimisations like copy-on-write becomes fairly trivial.

> I just reissued my SSL certificate, thanks to C++.

If you're referring to Heartbleed then OpenSSL is written in C, not C++. Generally only a language that inserts array bounds checks for every access would have shielded you from this bug... C++s does this if you use the at() function of , but op[] doesn't by default for performance reasons.

Re: Rust for C++ programmers – part 4: unique pointers

#55
post #43

Earlier quoted context omitted.

> Aligning memory is pretty important for high-performance apps using SSE/AVX Er… yes? Did I say it was unimportant anywhere? (also please note that I'm not a Rust developer) > Does Rust allow using memory allocated by specific external allocators? i.e. libnuma or something? I'm not quite sure what you're asking * if you're asking if it's possible to use arbitrary memory returned by a third party? Then yes. * if you'…

> Er… yes? Did I say it was unimportant anywhere? No, but that link seemed to indicate it wasn't being planned for the first release and pcwalton seems to think it's possible to get Rust programs to run as fast as C++ programs in most cases.

It can easily be added backward-compatibly, so could appear in, e.g., a 1.1 release. Or... someone who really wants it scratches their itch and gets it implemented. :)

(The speed of a language isn't determined by the speed of it's "first release".)

Re: Rust for C++ programmers – part 4: unique pointers

#56

Earlier quoted context omitted.

It could also be a memory leak. For example, I have a for loop that keeps requesting a new pointer...

I just tried the following: let mut blah = ~MyStruct{x: 3, y: 4}; for i in range(0,100000000) { blah = ~MyStruct{x: i + blah.x, y: i + blah.y}; } println!("{} {}", blah.x, blah.y); The memory usage didn't increase over time - the owned pointer frees when it gets reassigned.

See this example for more details: https://news.ycombinator.com/item?id=7665617

Re: Rust for C++ programmers – part 4: unique pointers

#57
post #54

Earlier quoted context omitted.

> If memory management is a serious problem for the software you work on, I've never found the boost library lacking. As a developer that isn't working with C++, I'm finding memory management in C++ to be a nightmare and no amount of libraries can solve it. Say you receive a pointer from somewhere. Is the referenced value allocated on the stack or on the heap? If allocated on the heap, do you need to free it yourself…

> Say you receive a pointer from somewhere. Here's your problem. In general I don't want to be receiving a single pointer from anyone. Lately, I've found it helpful to think of pointers in C++ as special iterators rather than a referential relic from C. In such a mindset passing pointers around without an accompanying end iterator, or iteration count, just makes no sense. Anywhere that implied iteration count is alwa…

The problem that Rust solves is that your advice, while good, is still advice. I absolutely agree that naked pointers are a code smell, and stack allocated objects should be the norm, with passing around (const) references to them. And RAII wrappers are great.

But all of that are patterns of use, enforced mostly by convention. In Rust, that's enforced by the language itself, and violating it will be a compiler error. The following kind of shenanigans won't be allowed outside of unsafe regions:

  int main()
  {
    int on_stack;
    int& ref = on_stack;
    int* ptr = static_cast(&ref);
    delete ptr;
    return 0;
  }
Yes, it's obviously bad code, but C++ happily let me write it, and it compiled with no warnings under -Wall -Wpedantic.

Re: Rust for C++ programmers – part 4: unique pointers

#58
post #57
post #54

Earlier quoted context omitted.

> Say you receive a pointer from somewhere. Here's your problem. In general I don't want to be receiving a single pointer from anyone. Lately, I've found it helpful to think of pointers in C++ as special iterators rather than a referential relic from C. In such a mindset passing pointers around without an accompanying end iterator, or iteration count, just makes no sense. Anywhere that implied iteration count is alwa…

The problem that Rust solves is that your advice, while good, is still advice . I absolutely agree that naked pointers are a code smell, and stack allocated objects should be the norm, with passing around (const) references to them. And RAII wrappers are great. But all of that are patterns of use, enforced mostly by convention. In Rust, that's enforced by the language itself, and violating it will be a compiler error…

This is because delete is an operator that can be overridden, and whether it has been overridden isn't known until link time.

    void operator delete(void*) {  }

    int main()
    {
      int on_stack;
      int& ref = on_stack;
      int* ptr = &ref;
      delete ptr;
      return 0;
    }
and now it's safe :P... and yes, never freeing any memory is arguably a perfectly valid memory management strategy. Ok, this example is nuts... but it's a feature of C++, in the C tradition, that it lets you do crazy things. Can I plug custom per-type memory allocators in to Rust?

Re: Rust for C++ programmers – part 4: unique pointers

#59
post #4

Rust looks very exciting and promising. I see the hardest things for it to be not necessarily syntax and concurrency (which are very well done), but performance and getting to compete with C++11 (C++14), which actually seems to become fresh and interesting again. Performance is tough. I feel most often C++ is not chosen for its inherent cleanliness, elegance and beauty, but because there are no viable competitors at…

Nobody will ever beat C/C++ for raw soft-real-time speed. Even a language like Rust that may have the linguistic features to be blazingly fast will never close that massive gap in historical optimization. Rust will never have an Intel-compiler.

That said, Rust will get close to C/C++ in ways that GC-based languages never will. GC languages mean memory bloat and soft-realtime problems related to GC cleaning. It will likely hit the sweet spot for a lot of embedded or gaming uses. Obviously you can do those tasks in other languages (great stuff is done on phones with GC-based languages, obviously), but you have to work around some challenges that would not exist in Rust.

Re: Rust for C++ programmers – part 4: unique pointers

#60
post #25
post #5

Earlier quoted context omitted.

I feel pretty good about it. For one, we have significantly better aliasing information than C++, and we use most of the guts, including all the optimizations and code generation, of a C++ compiler (clang/LLVM). There are also some optimizations around move semantics that are open to us but not for C++ as standardized. That said, there are definitely performance bugs that have yet to be fixed. But I would definitely…

How does one do intrinsics (SSE / AVX) in Rust - I guess they're just the exposed functions from emmintrin.h and the compiler calls them directly? How do you do ASM in Rust? Can you align memory in rust?

> How does one do intrinsics (SSE / AVX) in Rust - I guess they're just the exposed functions from emmintrin.h and the compiler calls them directly?

It uses the LLVM support.

> How do you do ASM in Rust?

With the asm! macro.

> Can you align memory in rust?

Yes. Write an allocator that does this and use it. The language doesn't have an allocator "built-in" and has full support for custom allocators.

Post reply on HN