FAQ

On Wed, Jan 7, 2015 at 4:14 AM, wrote:
On Wednesday, January 7, 2015 10:36:47 AM UTC+2, minux wrote:

On Wed, Jan 7, 2015 at 3:20 AM, wrote:

As discussed already, it is invalid to pass go pointers to cgo.
According to cgo wiki, there is C.CString function, that make copy from
go string to char*.
(Additional question, how this function make safe copy of go string, it
already run in cgo and GC work in parallel ?)
CString function is defined as: (cmd/cgo/out.go)
func _Cfunc_CString(s string) *_Ctype_char {
p := _cgo_runtime_cmalloc(uintptr(len(s)+1)) // this is C.malloc
pp := (*[1<<30]byte)(p)
copy(pp[:], s)
pp[len(s)] = 0
return (*_Ctype_char)(p)
}
But there is no equal function for byte slice.

The solution i came to, in addition to doubling memory allocations, also
double number of cgo calls:

package main

import (
//#include <stdlib.h>
//#include <string.h>
//int some_function( char *bytes, int num_bytes) {
// int i, sum = 0;
// for ( i = 0; i<num_bytes; i++) {
// sum += bytes[i];
// }
// return sum;
//}
"C"
"fmt"
)

func main() {
data := []byte{ 1, 2, 3, 4, 5, 6, 7, 8, 9}
cdata := C.malloc( C.size_t(len(data)))
copy( (*[1<<24]byte)(cdata)[0:len(data)], data)
fmt.Println( C.some_function( (*C.char)(cdata), C.int(len(data))) )
}

http://play.golang.org/p/lEB1aRWelZ

Is there a better way doing this ?
The correct way is to allocate the byte slice using C.malloc in the first
place.
(i.e. don't first create a []byte on Go heap, and then copy to C heap,
first
allocate C heap and then fill in the []byte)
Thanks for response,

some additional questions:
Does call to _cgo_runtime_cmalloc have overhead of cgo call ?
If not, is it safe to call _cgo_runtime_cmalloc instead of C.malloc ?
It's the same as C.malloc. After cgo rewrite, C.malloc becomes
_cgo_runtime_cmalloc (this is a special case implemented in
runtime). It will go through the same cgo call mechanism as
other cgo calls, so it also have the cgo overhead. (And no, you
can't directly call _cgo_runtime_cmalloc from your code: just use
C.malloc)

--
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+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Previous

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 4 of 4 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedJan 7, '15 at 8:20a
activeJan 7, '15 at 9:27a
posts4
users2
websitegolang.org

2 users in discussion

Djadala: 2 posts Minux: 2 posts

People

Translate

site design / logo © 2021 Grokbase