Skip to content
This repository has been archived by the owner on Feb 17, 2023. It is now read-only.

Commit

Permalink
Memory managed by Go can't be passed to C as of Go 1.6
Browse files Browse the repository at this point in the history
Discussion at:

    golang/go#12416
    https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md

Issues with the Go memory management code were hacked around by adding a
new check that ensured that pointers to memory managed by Go are never
passed to cgo code, since one can not be sure how and where pointers to
Go memory are being stored in the C code.

As a result, the memory must be manually malloc'd and free'd by cgo,
even if it's a Go object in the C memory. The userdata fix makes this
change explicit, by running a malloc and free using cgo, to explicitly
control the memory management.
  • Loading branch information
paultag committed Oct 7, 2016
1 parent 7e9c756 commit e3e7803
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
4 changes: 3 additions & 1 deletion webkit2/gasyncreadycallback.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ func newGAsyncReadyCallback(f interface{}) (cCallback C.GAsyncReadyCallback, use
if rf.Kind() != reflect.Func {
return nil, nil, errors.New("f is not a function")
}
cbinfo := &garCallback{rf}
data := C.malloc(C.size_t(unsafe.Sizeof(garCallback{})))
cbinfo := (*garCallback)(data)
cbinfo.f = rf
return C.GAsyncReadyCallback(C._gasyncreadycallback_call), C.gpointer(unsafe.Pointer(cbinfo)), nil
}
2 changes: 2 additions & 0 deletions webkit2/webview.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ func (v *WebView) RunJavaScript(script string, resultCallback func(result *gojs.
var err error
if resultCallback != nil {
callback := func(result *C.GAsyncResult) {
C.free(unsafe.Pointer(userData))
var jserr *C.GError
jsResult := C.webkit_web_view_run_javascript_finish(v.webView, result, &jserr)
if jsResult == nil {
Expand Down Expand Up @@ -189,6 +190,7 @@ func (v *WebView) GetSnapshot(resultCallback func(result *image.RGBA, err error)
var err error
if resultCallback != nil {
callback := func(result *C.GAsyncResult) {
C.free(unsafe.Pointer(userData))
var snapErr *C.GError
snapResult := C.webkit_web_view_get_snapshot_finish(v.webView, result, &snapErr)
if snapResult == nil {
Expand Down

0 comments on commit e3e7803

Please sign in to comment.