1) getpath() return a temp string, its c_str() pointer will be free out of function. So I use malloc 2) Assume we use the malloc way , are C.GoString() copying the pointer memory ? for we need C.free() malloc memory.
2017-04-19 14:17 GMT+08:00 Konstantin Khomoutov < flatw...@users.sourceforge.net>: > On Tue, 18 Apr 2017 18:09:03 -0700 (PDT) > hui zhang <fastfad...@gmail.com> wrote: > > > > > c code > > > > string getstring() {...} > > > > go > > > > string gostr = ????(C.getstring()) > > > Oh, and note that std::string is a fat object. > > > > > > So if getstring() really returns an instance of std::string, > > > and you need to actually extract its "raw bytes", you'd need to > > > call the c_str() method of std::string on that object before > > > applying the techniques from [1] to it. > > > > > > 1. https://github.com/golang/go/wiki/cgo#go-strings-and-c-strings > > > > > assume there is a c++ function string getpath() > > you mean I should do this ? > > > > char *CGetPath() { > > > auto str=getpath; > > > char *c = malloc(str.length()), > > > strcpy(c,str.c_str()); > > > return c; > > > } > > I beleive there's no need to do malloc() and copy the bytes over: > c_str () is defined to return to you a pointer to a contiguous array of > NUL-terminated representation of the string maintained by the > std::string instance. So you do (untested): > > char *CGetPath() { > return getpath().c_str(); > } > > and then in your Go code you do > > p := C.GoString(C.GetPath()) > > 2. http://en.cppreference.com/w/cpp/string/basic_string/c_str > -- 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.