bridge.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. //go:build windows
  2. package combridge
  3. import (
  4. "fmt"
  5. "runtime"
  6. "sync"
  7. "sync/atomic"
  8. )
  9. var (
  10. comIfcePointersL sync.RWMutex
  11. comIfcePointers = map[uintptr]*comObject{} // Map from ComInterfacePointer to the Go ComObject
  12. )
  13. // Resolve the GoInterface of the specified ComInterfacePointer
  14. func Resolve[T IUnknown](ifceP uintptr) T {
  15. comIfcePointersL.RLock()
  16. comObj := comIfcePointers[ifceP]
  17. comIfcePointersL.RUnlock()
  18. var n T
  19. if comObj != nil {
  20. t := comObj.resolve(ifceP)
  21. if t != nil {
  22. n = t.(T)
  23. }
  24. }
  25. return n
  26. }
  27. // New returns a new ComObject which implements the specified Com Interface, com calls will be redirected
  28. // to the specified go interface.
  29. func New[T IUnknown](obj T) *ComObject[T] {
  30. cObj := new(
  31. ifceDef[T]{obj},
  32. )
  33. return newComObject[T](cObj)
  34. }
  35. // New2 returns a new ComObject which implements the two specified Com Interfaces, com calls will be redirected
  36. // to those interfaces accordingly.
  37. // This is needed if a ComObject should implement two interfaces that are not descendants of each other,
  38. // then you get multiple inheritance.
  39. func New2[T IUnknown, T2 IUnknown](obj T, obj2 T2) *ComObject[T] {
  40. cObj := new(
  41. ifceDef[T]{obj},
  42. ifceDef[T2]{obj2},
  43. )
  44. return newComObject[T](cObj)
  45. }
  46. // new returns a new ComObject which implements multiple specified Com Interfaces, com calls will be redirected
  47. // to the specified go interfaces accordingly.
  48. // This is needed if a ComObject should implement multiple interfaces that are not descendants of each other,
  49. // then you get multiple inheritance.
  50. func new(impls ...ifceImpl) *comObject {
  51. impls = append([]ifceImpl{ifceDef[IUnknown]{}}, impls...)
  52. cObj := &comObject{
  53. refCount: 1,
  54. ifces: map[string]int{},
  55. ifcesImpl: make([]comInterfaceDesc, len(impls)),
  56. }
  57. for i, ifceDef := range impls {
  58. vtable, err := ifceDef.ifce()
  59. if err != nil {
  60. panic(err)
  61. }
  62. needsImplement := false
  63. for table := vtable; table != nil; table = table.Parent {
  64. guid := table.ComGUID
  65. if i, found := cObj.ifces[guid]; found {
  66. // This Interface is already implemented
  67. if guid == iUnknownGUID {
  68. // IUnknown is a special interface and never has an user specific implementation
  69. } else if cObj.ifcesImpl[i].impl != ifceDef.impl() {
  70. panic(fmt.Sprintf("Interface '%s' is already implemented by another object", table.Name))
  71. }
  72. break
  73. }
  74. needsImplement = true
  75. cObj.ifces[guid] = i
  76. }
  77. if !needsImplement {
  78. continue
  79. }
  80. ifceP, ifcePSlice := allocUintptrObject(1)
  81. ifcePSlice[0] = vtable.ComVTable
  82. cObj.ifcesImpl[i] = comInterfaceDesc{ifceP, ifceDef.impl()}
  83. }
  84. comIfcePointersL.Lock()
  85. for _, ifceImpl := range cObj.ifcesImpl {
  86. comIfcePointers[ifceImpl.ref] = cObj
  87. }
  88. comIfcePointersL.Unlock()
  89. return cObj
  90. }
  91. func newComObject[T IUnknown](comObj *comObject) *ComObject[T] {
  92. c := &ComObject[T]{obj: comObj}
  93. // Make sure to async release since release needs locks and might block the finalizer goroutine for a longer period
  94. runtime.SetFinalizer(c, func(obj *ComObject[T]) { obj.close(true) })
  95. return c
  96. }
  97. // ComObject describes an exported go instance to be used as a ComObject which implements
  98. // the specified Interface.
  99. type ComObject[T IUnknown] struct {
  100. obj *comObject
  101. closed int32
  102. }
  103. // Ref returns the native uintptr that points to the ComObject that is an interface pointer to T.
  104. // This can be used in native calls. If the object has been closed this function will panic.
  105. func (o *ComObject[T]) Ref() uintptr {
  106. if atomic.LoadInt32(&o.closed) != 0 {
  107. panic("ComObject has been released")
  108. }
  109. return o.obj.queryInterface(guidOf[T](), false)
  110. }
  111. // Close releases the native com object from the go side. It will only be destroyed if the ref counter
  112. // reaches zero.
  113. // After closing `Ref()` will panic.
  114. func (o *ComObject[T]) Close() error {
  115. o.close(false)
  116. return nil
  117. }
  118. // close releases the native com object from the go side. It will only be destroyed if the ref counter
  119. // reaches zero.
  120. // After closing `Ref()` will panic.
  121. func (o *ComObject[T]) close(asyncRelease bool) {
  122. if atomic.CompareAndSwapInt32(&o.closed, 0, 1) {
  123. runtime.SetFinalizer(o, nil)
  124. if asyncRelease {
  125. go o.obj.release()
  126. } else {
  127. o.obj.release()
  128. }
  129. }
  130. }
  131. type comInterfaceDesc struct {
  132. ref uintptr // The native Com InterfacePointer
  133. impl any // The golang target object
  134. }
  135. type comObject struct {
  136. l sync.Mutex
  137. refCount int32
  138. ifces map[string]int // Map of ComInterfaceGUID to Interface Slots
  139. ifcesImpl []comInterfaceDesc // Slots with InterfaceDescriptors
  140. }
  141. func (c *comObject) queryInterface(ifceGUID string, withAddRef bool) uintptr {
  142. c.l.Lock()
  143. defer c.l.Unlock()
  144. if c.refCount <= 0 {
  145. panic("call on released com object")
  146. }
  147. i, found := c.ifces[ifceGUID]
  148. if !found {
  149. return 0
  150. }
  151. if withAddRef {
  152. c.refCount++
  153. }
  154. return c.ifcesImpl[i].ref
  155. }
  156. func (c *comObject) resolve(ifceP uintptr) any {
  157. c.l.Lock()
  158. defer c.l.Unlock()
  159. if c.refCount <= 0 {
  160. panic("call on destroyed com object")
  161. }
  162. for _, ifce := range c.ifcesImpl {
  163. if ifce.ref != ifceP {
  164. continue
  165. }
  166. return ifce.impl
  167. }
  168. return nil
  169. }
  170. func (c *comObject) addRef() int32 {
  171. c.l.Lock()
  172. defer c.l.Unlock()
  173. if c.refCount <= 0 {
  174. panic("call on destroyed com object")
  175. }
  176. c.refCount++
  177. return c.refCount
  178. }
  179. func (c *comObject) release() int32 {
  180. c.l.Lock()
  181. defer c.l.Unlock()
  182. if c.refCount <= 0 {
  183. panic("call on destroyed com object")
  184. }
  185. if c.refCount--; c.refCount == 0 {
  186. comIfcePointersL.Lock()
  187. for _, ref := range c.ifcesImpl {
  188. delete(comIfcePointers, ref.ref)
  189. }
  190. comIfcePointersL.Unlock()
  191. for _, impl := range c.ifcesImpl {
  192. ref := impl.ref
  193. if ref == 0 {
  194. continue
  195. }
  196. globalFree(ref)
  197. }
  198. }
  199. return c.refCount
  200. }