Created
February 28, 2016 22:39
-
-
Save EntilZha/0f0fe80389be2f674111 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "ffitest" | |
version = "0.1.0" | |
authors = ["Pedro Rodriguez <[email protected]>"] | |
[dependencies] | |
[lib] | |
name = "ffitest" | |
crate-type = ["dylib"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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