我在用rust调用windows-rs来进行编程的时候,报错如下 |
| let f:LPTHREAD_START_ROUTINE =buffer;
| ---------------------- ^^^^^^ expected fn pointer, found *-ptr
| |
| expected due to this
|
= note: expected fn pointer unsafe extern "system" fn(*mut c_void) -> u32
found raw pointer *mut u8
报错代码:
let f:LPTHREAD_START_ROUTINE =buffer;
//(buffer 是 *mut u8指针,LPTHREAD_START_ROUTINE 是函数指针的别名
let t = CreateThread(ptr::null_mut(),0,Some(f), ptr::null_mut(), THREAD_CREATION_FLAGS(0), ptr::null_mut());
起因是我想通过rust将数据写入内存,然后调用windows中的CreateThread方法执行,但是我的第三个参数报错。报错为expected fn pointer unsafe extern "system" fn(*mut c_void) -> u32
, found raw pointer *mut u8
但我不知道如何将 *mut u8转换成函数指针,希望有大佬能不吝赐教,指点一番。十分感激!
CreateThread和 LPTHREAD_START_ROUTINE结构体如下。 pub unsafe fn CreateThread( lpthreadattributes: *mut SECURITY_ATTRIBUTES, dwstacksize: usize, lpstartaddress: Option<LPTHREAD_START_ROUTINE>, lpparameter: *mut c_void, dwcreationflags: THREAD_CREATION_FLAGS, lpthreadid: *mut u32 ) -> HANDLE
type LPTHREAD_START_ROUTINE = unsafe extern "system" fn(lpthreadparameter: *mut c_void) -> u32;
因为第三个参数是个泛型,所以我想通过Some()给他赋值。LPTHREAD_START_ROUTINE 是一个函数指针的别名,而我之前获得的是一个*mut u8型指针,我需要把这个 *mut u8型指针 转变成 LPTHREAD_START_ROUTINE
核心源码
use core::ffi::c_void; use std::ptr; mod bindings { windows::include_bindings!(); }
use bindings::{ Windows::Win32::System::Memory::{VirtualAlloc,MEM_COMMIT,VIRTUAL_ALLOCATION_TYPE,PAGE_PROTECTION_FLAGS}, Windows::Win32::System::Threading::{CreateThread,GetCurrentProcess,THREAD_CREATION_FLAGS}, Windows::Win32::System::LibraryLoader::{LoadLibraryA,GetProcAddress}, Windows::Win32::System::SystemServices::LPTHREAD_START_ROUTINE, Windows::Win32::System::Diagnostics::Debug::FlushInstructionCache, };
fn main(){
let payload: [u8; 340] = [0x65,0x78,.....(太长,省略)0x65,0x00 ];
unsafe {
let buffer = VirtualAlloc(ptr::null_mut(), 2000,VIRTUAL_ALLOCATION_TYPE(0x3000),PAGE_PROTECTION_FLAGS(0x40)) as *mut u8; //开辟内存
ptr::copy_nonoverlapping(payload.as_ptr(), buffer, 340); //数据赋值到buffer
let f:LPTHREAD_START_ROUTINE =buffer; //将buffer数据转换到指针函数中 (出错)
let t = CreateThread(ptr::null_mut(), 0,Some(f), ptr::null_mut(), THREAD_CREATION_FLAGS(0), ptr::null_mut());
WaitForSingleObject(t, -1);
}
Ext Link: https://microsoft.github.io/windows-docs-rs/doc/bindings/Windows/Win32/System/Threading/fn.CreateThread.html
评论区
写评论用md语法整理一下吧。不然别人怎么看。
你为什么要把这个函数的结果转化成*mut u8呢?
👇
Bai-Jinlin: std::mem::transmute
std::mem::transmute