On Wednesday, January 7, 2015 10:36:47 AM UTC+2, minux wrote:
On Wed, Jan 7, 2015 at 3:20 AM, <dja...@gmail.com <javascript:>> 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;

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))) )


Is there a better way doing this ?
The correct way is to allocate the byte slice using C.malloc in the first
(i.e. don't first create a []byte on Go heap, and then copy to C heap,
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 ?


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


Follow ups

Related Discussions

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

2 users in discussion

Djadala: 2 posts Minux: 2 posts



site design / logo © 2021 Grokbase