Commit a7d07d412c

dimenus <ryan.saunderson88@gmail.com>
2017-11-15 21:46:49
Added DLL loading capability in windows to the std lib.
1 parent 7a74dba
Changed files (3)
std/os/windows/index.zig
@@ -84,6 +84,11 @@ pub extern "kernel32" stdcallcc fn WriteFile(in_hFile: HANDLE, in_lpBuffer: &con
     in_nNumberOfBytesToWrite: DWORD, out_lpNumberOfBytesWritten: ?&DWORD,
     in_out_lpOverlapped: ?&OVERLAPPED) -> BOOL;
 
+//TODO: call unicode versions instead of relying on ANSI code page
+pub extern "kernel32" stdcallcc fn LoadLibraryA(lpLibFileName: LPCSTR) -> ?HMODULE;
+
+pub extern "kernel32" stdcallcc fn FreeLibrary(hModule: HMODULE) -> BOOL;   
+
 pub extern "user32" stdcallcc fn MessageBoxA(hWnd: ?HANDLE, lpText: ?LPCTSTR, lpCaption: ?LPCTSTR, uType: UINT) -> c_int;
 
 pub const PROV_RSA_FULL = 1;
@@ -97,6 +102,7 @@ pub const FLOAT = f32;
 pub const HANDLE = &c_void;
 pub const HCRYPTPROV = ULONG_PTR;
 pub const HINSTANCE = &@OpaqueType();
+pub const HMODULE = &@OpaqueType();
 pub const INT = c_int;
 pub const LPBYTE = &BYTE;
 pub const LPCH = &CHAR;
std/os/windows/util.zig
@@ -4,6 +4,7 @@ const windows = std.os.windows;
 const assert = std.debug.assert;
 const mem = std.mem;
 const BufMap = std.BufMap;
+const cstr = std.cstr;
 
 error WaitAbandoned;
 error WaitTimeOut;
@@ -149,3 +150,25 @@ pub fn createWindowsEnvBlock(allocator: &mem.Allocator, env_map: &const BufMap)
     result[i] = 0;
     return result;
 }
+
+error DllNotFound;
+pub fn windowsLoadDll(allocator: &mem.Allocator, dll_path: []const u8) -> %windows.HMODULE {
+    const padded_buff = %return cstr.addNullByte(allocator, dll_path);
+    defer allocator.free(padded_buff);
+    return windows.LoadLibraryA(padded_buff.ptr) ?? error.DllNotFound;
+}
+
+pub fn windowsUnloadDll(hModule: windows.HMODULE) {
+    assert(windows.FreeLibrary(hModule)!= 0);
+}
+
+
+test "InvalidDll" {
+    const DllName = "asdf.dll";
+    const allocator = std.debug.global_allocator;
+    const handle = os.windowsLoadDll(allocator, DllName) %%  |err| {
+        assert(err == error.DllNotFound);
+        return;
+    };
+}
+
std/os/index.zig
@@ -31,6 +31,8 @@ pub const windowsWaitSingle = windows_util.windowsWaitSingle;
 pub const windowsWrite = windows_util.windowsWrite;
 pub const windowsIsCygwinPty = windows_util.windowsIsCygwinPty;
 pub const windowsOpen = windows_util.windowsOpen;
+pub const windowsLoadDll = windows_util.windowsLoadDll;
+pub const windowsUnloadDll = windows_util.windowsUnloadDll; 
 pub const createWindowsEnvBlock = windows_util.createWindowsEnvBlock;
 
 pub const FileHandle = if (is_windows) windows.HANDLE else i32;