环境
❯ zig version
0.12.0-dev.286+b0d9bb0bb
dll
新建项目
mkdir dll
cd dll
zig init-lib
核心代码
main.zig
// To compile this, you could use this command " zig build-lib -lc -dynamic -fstrip -O ReleaseSmall src/main.zig"
const std = @import("std");
const win = std.os.windows;
// Types
const WINAPI = win.WINAPI;
const HINSTANCE = win.HINSTANCE;
const DWORD = win.DWORD;
const LPVOID = win.LPVOID;
const BOOL = win.BOOL;
const HWND = win.HWND;
const LPCSTR = win.LPCSTR;
const UINT = win.UINT;
// fdwReason parameter values
const DLL_PROCESS_ATTACH: DWORD = 1;
const DLL_THREAD_ATTACH: DWORD = 2;
const DLL_THREAD_DETACH: DWORD = 3;
const DLL_PROCESS_DETACH: DWORD = 0;
extern "user32" fn MessageBoxA(hWnd: ?HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT) callconv(WINAPI) i32;
pub export fn _DllMainCRTStartup(hinstDLL: HINSTANCE, fdwReason: DWORD, lpReserved: LPVOID) BOOL {
_ = lpReserved;
_ = hinstDLL;
switch (fdwReason) {
DLL_PROCESS_ATTACH => {
_ = MessageBoxA(null, "Hello World!", "Zig", 0);
},
DLL_THREAD_ATTACH => {},
DLL_THREAD_DETACH => {},
DLL_PROCESS_DETACH => {},
else => {},
}
return 1;
}
如果Dll被加载,就会弹个框。
编译
zig build-lib -lc -dynamic -fstrip -O ReleaseSmall src/main.zig
❯ ls main*
目录: E:\xk\Code\xkyss\xkyss.zig\playground\v0.12\dll
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2023/9/8 10:30 19968 main.dll
-a---- 2023/9/8 10:30 950 main.dll.obj
-a---- 2023/9/8 10:30 1146 main.lib
loader
新建项目
mkdir loader
cd loader
zig init-exe
核心代码
main.zig
const std = @import("std");
pub fn main() !void {
const dllpath =
// 绝对路径
// \\E:\xk\Code\xkyss\xkyss.zig\playground\v0.12\dll\main.dll
// 相对路径
\\../dll/main.dll
;
std.debug.print("Dll Path: {s}\n", .{dllpath});
// 加载dll
_ = try std.DynLib.open(dllpath);
}
运行
zig build run