Question

The Rust FFI guide (http://static.rust-lang.org/doc/master/guide-ffi.html) nicely demonstrates how to import C functions that use standard C types that are wrapped by the Rust std::lib library, such as size_t. But how do I bring C data structures defined in third party libraries into a Rust program?

I'm working with libmemcached, which has the following function:

memcached_st* memcached_create(memcached_st *ptr)

which is typically invoked like so in a C program (to kick things off):

#include <libmemcached/memcached.h>
// ...
memcached_st *memc;
memc = memcached_create(NULL);

The memcached_st is an opaque C struct - how do I declare and use that in a Rust program? Here are my failed attempts so far:

use std::libc::*;
use ptr;

#[link(name = "memcached")]
extern {
    struct memcached_st;  // error: unexpected token: `struct`
    memcached_st* memcached_create(memcached_st *ptr);
}

fn main() {
    unsafe {
        let memc = memcached_create(ptr:null());
        println!("{:?}", memc);
    }
}

and

use std::libc::*;
use ptr;

#[link(name = "memcached")]
extern {
    // error: unexpected token: `memcached_st`
    memcached_st* memcached_create(memcached_st *ptr);
}

fn main() {
    unsafe {
        let memc = memcached_create(ptr:null());
        println!("{:?}", memc);
    }
}
Was it helpful?

Solution

Using empty structure is a valid approach. You almost got it, you just don't need to put the struct definition in extern block. Also you can't use C code inside Rust sources - extern definitions have to follow standard Rust syntax.

use std::ptr;

struct memcached_st;

#[link(name = "memcached")]
extern {
    fn memcached_create(ptr: *memcached_st) -> *memcached_st;
}

fn main() {
    unsafe {
        let memc = memcached_create(ptr::null());
        println!("{:?}", memc);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top