Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use libc::c_char or std::os::raw::c_char?

Tags:

rust

ffi

I am writing a FFI wrapper for Rust. I have seen usages of both libc::c_char and std::os::raw::c_char. My knowledge of C is very minimal and I wonder if there is any difference. What should I use if I would like to expose a string to Python via cffi?

like image 907
colinfang Avatar asked Jun 08 '17 13:06

colinfang


2 Answers

I can't answer which is more idiomatic, but I can say that they are the same on 64-bit Linux (the default platform for most online hosted documentation):

std::os::raw::c_char:

type c_char = i8;

libc::c_char:

type c_char = i8;

Looking more broadly across different platforms is a bit more complicated. The standard library tightly groups all the definitions for c_char, but libc groups them by platform. Considering how fundamental this type is, I'd expect them to be the same on all platforms.

Practically speaking, neither of these definitions are likely to ever change, so there's probably not any stability difference.

My opinion would be to use the one from the standard library version until I needed to use something specific from libc, in which case I'd probably switch all the types to the libc variants, just to be consistent.

like image 182
Shepmaster Avatar answered Oct 19 '22 13:10

Shepmaster


In addition to @Shepmaster's answer, I'd like to highlight the fact that libc does not depend on std.

Therefore, if you can't use std, you'll have to use libc. This situation can be seen here.

Currently libc by default links to the standard library, but if you would instead like to use libc in a #![no_std] situation or crate you can request this via:

[dependencies]
libc = { version = "0.2", default-features = false }
like image 32
Centril Avatar answered Oct 19 '22 13:10

Centril