[rust-dev] How to allocate record on memory?

Niko Matsakis niko at alum.mit.edu
Tue Apr 17 14:13:54 PDT 2012


I don't *really* understand what you are trying to do, but I think you 
have two choices:

(1) A call to libc::malloc, like you showed in your later mail.

(2) Allocate the type as a @T and then use ptr::addr_of(*x) to get an 
unsafe ptr from that.  Then you are responsible for keeping a live 
reference to the @T so that we don't collect it.


Niko

On 4/15/12 5:51 PM, Alexander Stavonin wrote:
> I have a C function with void* argument wich will be passed to 
> callback and I want to pass Rust record as the argument. The question 
> is, how to allocate record on memory but not on the stack? I've tried 
> a lot of different ways, but with same result: in callback function 
> record data looked as already destroyed.
>
> example:
>
> ...
> type data_rec = {
>     on_connect_cb: fn@(listner: *evconnlistener, sock: c_int) -> bool,
>     data: int,
>     data1: int
> };
>
> fn re_listener_new_bind(ev_base: *event_base, flags: [listner_flags], 
> addr: sockaddr,
>             on_connect: fn@(listner: *evconnlistener, sock: c_int) -> 
> bool)
>         -> *evconnlistener unsafe {
> ...
> // initialising callback:
>
>     let callback = unsafe{ {on_connect_cb: on_connect, data: 10, 
> data1: -10} }; // will the record be allocated on the stack?
>     ret ev::evconnlistener_new_bind(ev_base, connect_callback, data, 
> res_flags, -1 as c_int,
>         ptr::addr_of(a), l as c_int);
> }
>
> crust fn connect_callback(listner: *evconnlistener, sock: c_int,
>     sockaddr: *c_void, len: c_int, ptr: *c_void) unsafe {
>
>     let data = ptr as *data_rec;
>     io::println(#fmt("%u, data: %d, data1 %d", ptr as uint, 
> (*data).data, (*data).data1));
> }
> ...
>
> console output:
>
> 1088426520, data: 1088426784, data1 146814400
>
> expected output:
> 1088426520, data: 10, data1 -10
>
>
>
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev



More information about the Rust-dev mailing list