github.com/hspan/go-ole@v0.0.0/winrt.go (about) 1 // +build windows 2 3 package ole 4 5 import ( 6 "reflect" 7 "syscall" 8 "unicode/utf8" 9 "unsafe" 10 ) 11 12 var ( 13 procRoInitialize = modcombase.NewProc("RoInitialize") 14 procRoActivateInstance = modcombase.NewProc("RoActivateInstance") 15 procRoGetActivationFactory = modcombase.NewProc("RoGetActivationFactory") 16 procWindowsCreateString = modcombase.NewProc("WindowsCreateString") 17 procWindowsDeleteString = modcombase.NewProc("WindowsDeleteString") 18 procWindowsGetStringRawBuffer = modcombase.NewProc("WindowsGetStringRawBuffer") 19 ) 20 21 func RoInitialize(thread_type uint32) (err error) { 22 hr, _, _ := procRoInitialize.Call(uintptr(thread_type)) 23 if hr != 0 { 24 err = NewError(hr) 25 } 26 return 27 } 28 29 func RoActivateInstance(clsid string) (ins *IInspectable, err error) { 30 hClsid, err := NewHString(clsid) 31 if err != nil { 32 return nil, err 33 } 34 defer DeleteHString(hClsid) 35 36 hr, _, _ := procRoActivateInstance.Call( 37 uintptr(unsafe.Pointer(hClsid)), 38 uintptr(unsafe.Pointer(&ins))) 39 if hr != 0 { 40 err = NewError(hr) 41 } 42 return 43 } 44 45 func RoGetActivationFactory(clsid string, iid *GUID) (ins *IInspectable, err error) { 46 hClsid, err := NewHString(clsid) 47 if err != nil { 48 return nil, err 49 } 50 defer DeleteHString(hClsid) 51 52 hr, _, _ := procRoGetActivationFactory.Call( 53 uintptr(unsafe.Pointer(hClsid)), 54 uintptr(unsafe.Pointer(iid)), 55 uintptr(unsafe.Pointer(&ins))) 56 if hr != 0 { 57 err = NewError(hr) 58 } 59 return 60 } 61 62 // HString is handle string for pointers. 63 type HString uintptr 64 65 // NewHString returns a new HString for Go string. 66 func NewHString(s string) (hstring HString, err error) { 67 u16 := syscall.StringToUTF16Ptr(s) 68 len := uint32(utf8.RuneCountInString(s)) 69 hr, _, _ := procWindowsCreateString.Call( 70 uintptr(unsafe.Pointer(u16)), 71 uintptr(len), 72 uintptr(unsafe.Pointer(&hstring))) 73 if hr != 0 { 74 err = NewError(hr) 75 } 76 return 77 } 78 79 // DeleteHString deletes HString. 80 func DeleteHString(hstring HString) (err error) { 81 hr, _, _ := procWindowsDeleteString.Call(uintptr(hstring)) 82 if hr != 0 { 83 err = NewError(hr) 84 } 85 return 86 } 87 88 // String returns Go string value of HString. 89 func (h HString) String() string { 90 var u16buf uintptr 91 var u16len uint32 92 u16buf, _, _ = procWindowsGetStringRawBuffer.Call( 93 uintptr(h), 94 uintptr(unsafe.Pointer(&u16len))) 95 96 u16hdr := reflect.SliceHeader{Data: u16buf, Len: int(u16len), Cap: int(u16len)} 97 u16 := *(*[]uint16)(unsafe.Pointer(&u16hdr)) 98 return syscall.UTF16ToString(u16) 99 }