rust DllMain

wangki·2025년 4월 8일
0

Rust

목록 보기
31/55

개요

rust에서 dll로 빌드 시 진입지점인 DllMain을 만들어서 테스트한다.

내용

// cargo.toml
[lib]
crate-type = ["cdylib"]
[dependencies.windows]
version = "*"
features = [
    "Win32_Foundation",
    "Win32_System_SystemServices",
    "Win32_UI_WindowsAndMessaging",
]
use std::ffi::{c_void, CString};

use macro_test::my_attr;
use windows::{core::PCSTR, Win32::{Foundation::*, System::SystemServices::*, UI::WindowsAndMessaging::{MessageBoxA, MB_OK}}};

#[unsafe(no_mangle)]
#[allow(non_snake_case, unused_variables)]
pub extern "system" fn DllMain(dll_module: HINSTANCE, fdw_reason: u32, _: *mut ()) -> bool {
    match fdw_reason {
        DLL_PROCESS_ATTACH => {  // DLL_PROCESS_ATTACH
            println!("attach!");
            test_func("attach");
        }
        DLL_PROCESS_DETACH => {
            println!("detach!");
            test_func("detach");
        }
        _ => {
        
        }
    }
    true
}


#[my_attr]
fn test_func(value: &str) {
    unsafe {
        let content = CString::new(value).unwrap();
        let title = CString::new("title").unwrap();

        MessageBoxA(None, PCSTR(content.as_ptr() as *const u8), PCSTR(title.as_ptr() as *const u8), MB_OK);
    }
}

windows crates를 이용하여 DllMain을 만든다.
빌드를 하게되면 ./target/debug 디렉토리에 dll파일이 생성된다.

c++ 콘솔프로그램에서 rust로 생성한 dll을 호출한다.

#include <iostream>
#include <windows.h>

int main()
{
    HMODULE module = LoadLibraryA("d:\\work\\rust\\test\\test_20250408\\target\\debug\\test_20250408.dll");
	if (module == NULL) {
		std::cerr << "Failed to load the DLL" << std::endl;
		return 1;
	}

	FreeLibrary(module);

	std::cout << "Hello World!\n";
	return 0;
}

순서대로 메시지박스가 나온다.

전체 소스
https://github.com/wangki-kyu/rust_study/tree/main/dll_main_test

결론

rust에서도 cpp에서 dll을 만드는 것 처럼 DllMain을 통해서 진입시점에 사용자 로직을 작성할 수 있다.

0개의 댓글