c代码如下
static inline void **alignPointer(void **ptr, size_t alignment) {
return (void **)((intptr_t)((unsigned char *)ptr + alignment - 1) & -alignment);
}
extern "C" void *MemoryAllocAlign(size_t size, size_t alignment) {
ASSERT(size > 0);
void **origin = (void **)malloc(size + sizeof(void *) + alignment);
ASSERT(origin != NULL);
if (!origin) {
return NULL;
}
void **aligned = alignPointer(origin + 1, alignment);
aligned[-1] = origin;
return aligned;
}
extern "C" void MemoryFreeAlign(void *aligned) {
if (aligned) {
void *origin = ((void **)aligned)[-1];
free(origin);
}
}
我实现的rust部分代码
[cfg_attr(feature = "cargo-clippy", allow(clippy::inline_always))]
#[inline(always)]
fn align_size(v: size_t, n: size_t) -> size_t {
v.wrapping_add(n).wrapping_sub(1) & !n.wrapping_sub(1)
}
#[cfg_attr(feature = "cargo-clippy", allow(clippy::inline_always))]
#[inline(always)]
fn align_ptr(v: *mut *mut c_void, n: size_t) -> *mut *mut c_void {
unsafe {
((v as size_t).wrapping_add(n).wrapping_sub(1) & !n.wrapping_sub(1)) as *mut *mut c_void
}
}
use core::mem::size_of;
use core::slice;
pub unsafe trait MyAlloc{
unsafe fn fast_malloc(&self, size: size_t, alignment: size_t) -> *mut c_void {
if cfg!(target_os = "linux") && unlikely(size == 0) {
return ptr::null_mut();
}
unsafe{
let udata = libc::malloc(size + size_of::<*mut c_void>() as size_t + alignment)as *mut c_uchar;
if udata.is_null(){
return ptr::null_mut();
}
let adata = align_ptr( (&mut udata as *mut *mut c_uchar as *mut *mut c_void).wrapping_add(1),alignment);
//adata[-1] = udata; 这部分不知道怎么实现。。。。
//return adata;
}
}
}
希望大佬帮忙看看,没有问题
1
共 0 条评论, 1 页
评论区
写评论还没有评论