In Rust how can I define or import a C struct from a third party library?

StackOverflow https://stackoverflow.com/questions/22116547

  •  18-10-2022
  •  | 
  •  

Pregunta

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);
    }
}
¿Fue útil?

Solución

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);
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top