e been violating cgo rules by passing Go pointer to an integer to the C code for storage.
C.nlopt_set_max_objective(n.gopt, (C.nlopt_func)(unsafe.Pointer(C.callback_adaptor)), unsafe.Pointer(&nID)) Now I do it like this instead: C.nlopt_set_max_objective(n.gopt, (C.nlopt_func)(unsafe.Pointer(C.callback_adaptor)), unsafe.Pointer(uintptr(nID))) And the problem is gone. Thanks for your help, Iakov On Thursday, November 10, 2016 at 3:32:02 PM UTC+1, iakov....@gmail.com wrote: > > Hi, > I don't have a minimal example yet, but this looks very suspicious. It > seems that sometimes defer called before the function finishes, if cgo code > with callbacks is called in it. > > Here's the code: > > func (n *NLOPT) Run(iterations int) { > log.Debug("entering Run method") > ... > nID := registerObject(n) > defer unregisterObject(nID) > ... > // this will call some go function > n.optRes = C.nlopt_optimize(n.gopt, > (*C.double)(unsafe.Pointer(&x[0])), &maxf) > .... > log.Debug("leaving Run method") > } > > > Here's what I see in my logs: > > entering Run method > register: 1 (0xc82000a900) > ... other messages, no "leaving Run method" ... > unregister: 1 (0xc82000a900) > panic: interface conversion: interface {} is nil, not *optimize.NLOPT > (this panic happens because something was prematurely unregistered) > > So defer is executed before the method exits. > > I tried this in go v1.5 and v1.7, linux64. Sometimes it happens not > immediately, but after some time. > > Are there any special defer rules regarding cgo & callbacks which I do not > know? > > Thanks a lot for your suggestions, > Iakov > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.