urs*_*rei 17 python ctypes rust
根据这些 答案,我现在定义了一个Rust 1.0函数,如下所示,以便可以使用Python从Python调用ctypes:
use std::vec;
extern crate libc;
use libc::{c_int, c_float, size_t};
use std::slice;
#[no_mangle]
pub extern fn convert_vec(input_lon: *const c_float,
lon_size: size_t,
input_lat: *const c_float,
lat_size: size_t) -> Vec<(i32, i32)> {
let input_lon = unsafe {
slice::from_raw_parts(input_lon, lon_size as usize)
};
let input_lat = unsafe {
slice::from_raw_parts(input_lat, lat_size as usize)
};
let combined: Vec<(i32, i32)> = input_lon
.iter()
.zip(input_lat.iter())
.map(|each| convert(*each.0, *each.1))
.collect();
return combined
}
Run Code Online (Sandbox Code Playgroud)
我正在设置Python部分:
from ctypes import *
class Int32_2(Structure):
_fields_ = [("array", c_int32 * 2)]
rust_bng_vec = lib.convert_vec_py
rust_bng_vec.argtypes = [POINTER(c_float), c_size_t,
POINTER(c_float), c_size_t]
rust_bng_vec.restype = POINTER(Int32_2)
Run Code Online (Sandbox Code Playgroud)
这似乎没问题,但我是:
combined(a Vec<(i32, i32)>)转换为C兼容的结构,因此可以将其返回到我的Python脚本.return &combined?)以及如果我这样做,我将如何使用适当的生命周期说明符来注释该函数She*_*ter 19
最值得注意的是C中没有元组这样的东西 .C是图书馆互操作性的通用语言,你将被要求限制自己使用这种语言的能力.如果你在Rust和另一种高级语言之间进行交谈并不重要; 你必须说C.
C中可能没有元组,但有structs.一个双元素元组只是一个有两个成员的结构!
让我们从我们要编写的C代码开始:
#include <stdio.h>
#include <stdint.h>
typedef struct {
uint32_t a;
uint32_t b;
} tuple_t;
typedef struct {
void *data;
size_t len;
} array_t;
extern array_t convert_vec(array_t lat, array_t lon);
int main() {
uint32_t lats[3] = {0, 1, 2};
uint32_t lons[3] = {9, 8, 7};
array_t lat = { .data = lats, .len = 3 };
array_t lon = { .data = lons, .len = 3 };
array_t fixed = convert_vec(lat, lon);
tuple_t *real = fixed.data;
for (int i = 0; i < fixed.len; i++) {
printf("%d, %d\n", real[i].a, real[i].b);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们已经定义了两个structs - 一个代表我们的元组,另一个代表一个数组,因为我们将来回传递一些.
我们将通过在Rust中定义完全相同的结构来定义它们,并将它们定义为具有完全相同的成员(类型,顺序,名称).重要的是,我们使用#[repr(C)]Rust编译器知道在重新排序数据时不做任何有趣的事情.
extern crate libc;
use std::slice;
use std::mem;
#[repr(C)]
pub struct Tuple {
a: libc::uint32_t,
b: libc::uint32_t,
}
#[repr(C)]
pub struct Array {
data: *const libc::c_void,
len: libc::size_t,
}
impl Array {
unsafe fn as_u32_slice(&self) -> &[u32] {
assert!(!self.data.is_null());
slice::from_raw_parts(self.data as *const u32, self.len as usize)
}
fn from_vec<T>(mut vec: Vec<T>) -> Array {
// Important to make length and capacity match
// A better solution is to track both length and capacity
vec.shrink_to_fit();
let array = Array { data: vec.as_ptr() as *const libc::c_void, len: vec.len() as libc::size_t };
// Whee! Leak the memory, and now the raw pointer (and
// eventually C) is the owner.
mem::forget(vec);
array
}
}
#[no_mangle]
pub extern fn convert_vec(lon: Array, lat: Array) -> Array {
let lon = unsafe { lon.as_u32_slice() };
let lat = unsafe { lat.as_u32_slice() };
let vec =
lat.iter().zip(lon.iter())
.map(|(&lat, &lon)| Tuple { a: lat, b: lon })
.collect();
Array::from_vec(vec)
}
Run Code Online (Sandbox Code Playgroud)
我们绝不能repr(C)在FFI边界上接受或返回非类型,所以我们通过我们的Array.请注意,有大量unsafe代码,因为我们必须将未知指针转换为data(c_void)到特定类型.这是C世界中通用的代价.
让我们现在转向Python.基本上,我们只需要模仿C代码的作用:
import ctypes
class FFITuple(ctypes.Structure):
_fields_ = [("a", ctypes.c_uint32),
("b", ctypes.c_uint32)]
class FFIArray(ctypes.Structure):
_fields_ = [("data", ctypes.c_void_p),
("len", ctypes.c_size_t)]
# Allow implicit conversions from a sequence of 32-bit unsigned
# integers.
@classmethod
def from_param(cls, seq):
return cls(seq)
# Wrap sequence of values. You can specify another type besides a
# 32-bit unsigned integer.
def __init__(self, seq, data_type = ctypes.c_uint32):
array_type = data_type * len(seq)
raw_seq = array_type(*seq)
self.data = ctypes.cast(raw_seq, ctypes.c_void_p)
self.len = len(seq)
# A conversion function that cleans up the result value to make it
# nicer to consume.
def void_array_to_tuple_list(array, _func, _args):
tuple_array = ctypes.cast(array.data, ctypes.POINTER(FFITuple))
return [tuple_array[i] for i in range(0, array.len)]
lib = ctypes.cdll.LoadLibrary("./target/debug/libtupleffi.dylib")
lib.convert_vec.argtypes = (FFIArray, FFIArray)
lib.convert_vec.restype = FFIArray
lib.convert_vec.errcheck = void_array_to_tuple_list
for tupl in lib.convert_vec([1,2,3], [9,8,7]):
print tupl.a, tupl.b
Run Code Online (Sandbox Code Playgroud)
原谅我的基本Python.我相信一个经验丰富的Pythonista可以让它看起来更漂亮!感谢@eryksun提供了一些关于如何让消费者方面更好地调用方法的好建议.
在这个示例代码中,我们泄漏了由分配的内存Vec.从理论上讲,FFI代码现在拥有内存,但实际上,它无法对它做任何有用的事情.要拥有一个完全正确的示例,您需要添加另一个方法来接受来自被调用者的指针,将其转换回a Vec,然后允许Rust删除该值.这是唯一安全的方法,因为Rust几乎可以保证使用与FFI语言使用的内存分配器不同的内存分配器.
不确定我是否应该返回一个引用,如果我这样做,我将如何使用适当的生命周期说明符来注释该函数
不,你不想(读:不能)返回一个引用.如果可以,那么项目的所有权将以函数调用结束,并且引用将指向任何内容.这就是为什么我们需要与mem::forget原始指针进行两步跳舞并返回原始指针.
| 归档时间: |
|
| 查看次数: |
1270 次 |
| 最近记录: |