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
을 통해서 진입시점에 사용자 로직을 작성할 수 있다.