@@ -75,7 +75,7 @@ type VirtualMachine struct {
7575
7676 * pointer
7777 dispatchQueue unsafe.Pointer
78- stateHandle cgo. Handle
78+ stateHandle * machineState
7979
8080 finalizeOnce sync.Once
8181}
@@ -103,18 +103,19 @@ func NewVirtualMachine(config *VirtualMachineConfiguration) (*VirtualMachine, er
103103 cs := (* char )(objc .GetUUID ())
104104 dispatchQueue := C .makeDispatchQueue (cs .CString ())
105105
106- stateHandle := cgo . NewHandle ( & machineState {
106+ stateHandle := & machineState {
107107 state : VirtualMachineState (0 ),
108108 stateNotify : infinity .NewChannel [VirtualMachineState ](),
109- })
109+ }
110110
111+ stateHandlePtr := cgo .NewHandle (stateHandle )
111112 v := & VirtualMachine {
112113 id : cs .String (),
113114 pointer : objc .NewPointer (
114115 C .newVZVirtualMachineWithDispatchQueue (
115116 objc .Ptr (config ),
116117 dispatchQueue ,
117- unsafe .Pointer (& stateHandle ),
118+ unsafe .Pointer (& stateHandlePtr ),
118119 ),
119120 ),
120121 dispatchQueue : dispatchQueue ,
@@ -123,6 +124,7 @@ func NewVirtualMachine(config *VirtualMachineConfiguration) (*VirtualMachine, er
123124
124125 objc .SetFinalizer (v , func (self * VirtualMachine ) {
125126 self .finalize ()
127+ stateHandlePtr .Delete ()
126128 })
127129 return v , nil
128130}
@@ -165,30 +167,18 @@ func changeStateOnObserver(newStateRaw C.int, cgoHandlerPtr unsafe.Pointer) {
165167 v .mu .Unlock ()
166168}
167169
168- //export deleteStateHandler
169- func deleteStateHandler (cgoHandlerPtr unsafe.Pointer ) {
170- stateHandler := * (* cgo .Handle )(cgoHandlerPtr )
171- stateHandler .Delete ()
172- }
173-
174170// State represents execution state of the virtual machine.
175171func (v * VirtualMachine ) State () VirtualMachineState {
176- // I expected it will not cause panic.
177- // if caused panic, that's unexpected behavior.
178- val , _ := v .stateHandle .Value ().(* machineState )
179- val .mu .RLock ()
180- defer val .mu .RUnlock ()
181- return val .state
172+ v .stateHandle .mu .RLock ()
173+ defer v .stateHandle .mu .RUnlock ()
174+ return v .stateHandle .state
182175}
183176
184177// StateChangedNotify gets notification is changed execution state of the virtual machine.
185178func (v * VirtualMachine ) StateChangedNotify () <- chan VirtualMachineState {
186- // I expected it will not cause panic.
187- // if caused panic, that's unexpected behavior.
188- val , _ := v .stateHandle .Value ().(* machineState )
189- val .mu .RLock ()
190- defer val .mu .RUnlock ()
191- return val .stateNotify .Out ()
179+ v .stateHandle .mu .RLock ()
180+ defer v .stateHandle .mu .RUnlock ()
181+ return v .stateHandle .stateNotify .Out ()
192182}
193183
194184// CanStart returns true if the machine is in a state that can be started.
0 commit comments