Skip to content

Instantly share code, notes, and snippets.

@duanebester
Last active October 1, 2015 23:23
Show Gist options
  • Save duanebester/82a9bada152965e42204 to your computer and use it in GitHub Desktop.
Save duanebester/82a9bada152965e42204 to your computer and use it in GitHub Desktop.
Enter your USB Vendor ID and print the "Friendly Name"
package main
/*
#cgo LDFLAGS: -lSetupapi
#ifdef __MINGW32__
#include <ntdef.h>
#endif
#include <windows.h>
#include <setupapi.h>
*/
import "C"
import (
"fmt"
"strings"
"unsafe"
)
type callCFn func(buf unsafe.Pointer, bufSize *C.DWORD) unsafe.Pointer
// simple helper function for this windows
// "call a function twice to get the amount of space that needs to be allocated" stuff
func getCString(fnCall callCFn) string {
var requiredSize C.DWORD
fnCall(nil, &requiredSize)
if requiredSize <= 0 {
return ""
}
buffer := C.malloc((C.size_t)(requiredSize))
defer C.free(buffer)
strPt := fnCall(buffer, &requiredSize)
return C.GoString((*C.char)(strPt))
}
func FindFriendlyNameOfVendorId(expectedVID string) {
var ClassGuid C.GUID
cStr := C.CString("USB")
defer C.free(unsafe.Pointer(cStr))
deviceInfoSet := C.SetupDiGetClassDevs(&ClassGuid, (*C.CHAR)(cStr), nil, C.DIGCF_PRESENT|C.DIGCF_ALLCLASSES)
defer C.SetupDiDestroyDeviceInfoList(deviceInfoSet)
var i C.DWORD
var devinfoData C.SP_DEVINFO_DATA
devinfoData.cbSize = C.DWORD(unsafe.Sizeof(devinfoData))
for i = 0; ; i++ {
if res := C.SetupDiEnumDeviceInfo(deviceInfoSet, i, &devinfoData); res == 0 {
break
}
classStr := getCString(func(buffer unsafe.Pointer, size *C.DWORD) unsafe.Pointer {
C.SetupDiGetDeviceRegistryProperty(deviceInfoSet, &devinfoData, C.SPDRP_HARDWAREID, nil, (*C.BYTE)(buffer), *size, size)
return buffer
})
if strings.Contains(classStr, expectedVID) {
friendlyName := getCString(func(buffer unsafe.Pointer, size *C.DWORD) unsafe.Pointer {
C.SetupDiGetDeviceRegistryProperty(deviceInfoSet, &devinfoData, C.SPDRP_FRIENDLYNAME, nil, (*C.BYTE)(buffer), *size, size)
return buffer
})
fmt.Println(friendlyName)
}
}
}
func main() {
FindFriendlyNameOfVendorId("VID_XXXX")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment