Skip to content

Instantly share code, notes, and snippets.

@fdb
Last active December 5, 2017 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fdb/a2ae472305632bf8814d46d7957636f1 to your computer and use it in GitHub Desktop.
Save fdb/a2ae472305632bf8814d46d7957636f1 to your computer and use it in GitHub Desktop.
Dynamically loading Windows function with GetProcAddress
[package]
name = "procaddress"
version = "0.1.0"
authors = []
[dependencies]
libc = "0.2.33"
extern crate libc;
use std::ptr;
#[link(name = "kernel32")]
#[link(name = "user32")]
extern "stdcall" {
pub fn LoadLibraryA(lpFileName: *const u8) -> *const usize;
pub fn GetProcAddress(hModule: *const usize, lpProcName: *const u8) -> *const usize;
pub fn MessageBoxA(hWnd: *const usize, lpText: *const u8, lpCaption: *const u8, uType: u32)
-> i32;
}
type FnMessageBox = extern "stdcall" fn(*const (), *const u8, *const u8, u32) -> i32;
fn main() {
unsafe {
MessageBoxA(
ptr::null(),
MESSAGE.as_ptr() as *const u8,
TITLE.as_ptr() as *const u8,
0,
);
let module = LoadLibraryA(USER32_DLL.as_ptr() as *const u8);
println!("module {}", module as usize);
let h_message_box = GetProcAddress(module, MESSAGE_BOX.as_ptr() as *const u8);
println!("MessageBoxA {}", h_message_box as usize);
let message_box = std::mem::transmute::<*const usize, FnMessageBox>(h_message_box);
message_box(
ptr::null(),
MESSAGE.as_ptr() as *const u8,
TITLE.as_ptr() as *const u8,
0,
);
}
}
const USER32_DLL: &'static [u8] = b"user32\0";
const MESSAGE_BOX: &'static [u8] = b"MessageBoxA\0";
const TITLE: &'static [u8] = b"GetProcAddress\0";
const MESSAGE: &'static [u8] = b"Hello, World!\0";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment