Skip to content

Instantly share code, notes, and snippets.

@timsneath
Created March 3, 2024 00:46
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 timsneath/a437e09f6cd282d08827289f8e04356b to your computer and use it in GitHub Desktop.
Save timsneath/a437e09f6cd282d08827289f8e04356b to your computer and use it in GitHub Desktop.
Simple example of calling classic Windows APIs from Swift
import WinSDK
// Call a simple Win32 function and pass in strings
MessageBoxA(nil, "Hello from Swift running on Windows", "Swift Message Box", UINT(MB_OK))
// Call a Win32 function that passes a variable by pointer
var memorySizeInBytes: LONGLONG = 0
GetPhysicallyInstalledSystemMemory(&memorySizeInBytes)
print("System has \(memorySizeInBytes / 1024 / 1024)GB of RAM installed.");
// Create a String and pass its pointer to a Win32 function
let desktopPath = String(unsafeUninitializedCapacity: Int(MAX_PATH)) { buffer in
SHGetFolderPathA(nil, CSIDL_DESKTOP, nil, 0, buffer.baseAddress)
return buffer.firstIndex(of: 0) ?? 0 // tell Swift where the string ends
}
print("Desktop folder is at \(desktopPath)")
// Create a struct and use it to interrogate system battery life
var powerStatus = SYSTEM_POWER_STATUS()
let hr = GetSystemPowerStatus(&powerStatus)
let systemHasBattery = powerStatus.BatteryFlag < 128
let batteryLifePercent = powerStatus.BatteryLifePercent
if systemHasBattery {
print("System has a battery. Battery life remaining: \(batteryLifePercent)%")
} else {
print("System has no battery.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment