TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Rust FFI: Sending strings to the outside world

22 pointsby huydotnetabout 8 years ago

7 comments

ekiddabout 8 years ago
It&#x27;s nice to see a demonstration of how to do this by hand! But at work, we use Neon <a href="https:&#x2F;&#x2F;github.com&#x2F;neon-bindings&#x2F;neon" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;neon-bindings&#x2F;neon</a> to write production Node.js modules in Rust.
评论 #14336365 未加载
Veedracabout 8 years ago
<p><pre><code> #[no_mangle] pub extern fn string_array() -&gt; *const *const u8 { let v = vec![ &quot;Hello\0&quot;.as_ptr(), &quot;World\0&quot;.as_ptr() ]; v.as_ptr() } </code></pre> This has exactly the same problem as with `CString`; the `Vec` is deallocated at function exit.
评论 #14336402 未加载
GlitchMrabout 8 years ago
And there is a memory leak in all of that.
评论 #14336257 未加载
评论 #14364788 未加载
masklinnabout 8 years ago
&gt; First, we store the Pointer of s string in a variable (p).<p>&gt; Then we use std::mem::forget to release it from the responsibility of Rust.<p>CString::into_raw does that whole song and dance for you.<p>For Vectors you probably want to convert them to boxed slices first, at which point you can use Box::into_raw (to get the slice&#x27;s head pointer).
zackmorrisabout 8 years ago
I think the article inadvertently reinforces the idea that it&#x27;s really only practical to scale code that segregates processes and uses streams instead of shared memory. New languages should probably focus on things like the Actor model and optimize stream passing with things like copy-on-write so that no data is actually copied until it&#x27;s mutated.<p>For this and many other reasons (mainly pushing the onus of managing memory onto the developer instead of automating it) I can&#x27;t really get behind Rust. I think many other languages like Swift are also barking up the wrong tree by being too pedantic.
评论 #14338443 未加载
评论 #14337656 未加载
Michael-F-Bryanabout 8 years ago
I&#x27;d recommend against using `std::mem::forget`. Even though it does pretty much the same thing you should probably use `some_cstring.into_raw()` instead. Semantically it&#x27;s indicating that you are passing ownership of the string to the caller, while `forget()` just indicates that you want to leak the thing.
cryptarchabout 8 years ago
To the author: it would be nice if your site had a small screens layout.<p>I can&#x27;t read the article on my phone because too much code is cut off (and the right margin is unpleasantly close to the main text, unlike the left margin).
评论 #14336622 未加载