Skip to content

Instantly share code, notes, and snippets.

@EntilZha
Created February 28, 2016 22:39
Show Gist options
  • Save EntilZha/0f0fe80389be2f674111 to your computer and use it in GitHub Desktop.
Save EntilZha/0f0fe80389be2f674111 to your computer and use it in GitHub Desktop.
[package]
name = "ffitest"
version = "0.1.0"
authors = ["Pedro Rodriguez <[email protected]>"]
[dependencies]
[lib]
name = "ffitest"
crate-type = ["dylib"]
use std::ffi::{CString, CStr};
use std::os::raw::{c_uint, c_char};
#[no_mangle]
pub extern fn substring(str_input: *const c_char, i: c_uint, j: c_uint) -> *const c_char {
unsafe {
let slice = CStr::from_ptr(str_input);
let rust_str = slice.to_str().unwrap();
let rust_i = i as usize;
let rust_j = j as usize;
let rust_substr = &rust_str[rust_i..rust_j];
let rust_cstr = CString::new(rust_substr).unwrap();
rust_cstr.as_ptr()
}
}
$ cargo build --release
Compiling ffitest v0.1.0 (file:///private/tmp/ffitest)
$ ipython
In [1]: import ctypes
In [2]: ffitest = ctypes.cdll.LoadLibrary("target/release/libffitest.dylib")
In [3]: ffitest.substring.argtypes = (ctypes.c_char_p, ctypes.c_int, ctypes.c_int)
In [4]: ffitest.substring.restype = ctypes.c_char_p
In [5]: ffitest.substring(b"testing", 2, 4)
Out[5]: b'st'
In [6]: ffitest.substring(b"testing", 2, 5)
Out[6]: b'sti'
In [7]: ffitest.substring(b"testing", 2, 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment