Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

go - How to manipulate a C character array inside a cgo function?

I have a C function, that is calling a go-Function with an char array parameter. The go-Function has to modify the content of the parameter. How to accomplish this?

void cFunction() {
 char buffer[9] = "aaabbbccc"; // 9 is in this case correct, it is not a null-terminated-string
 goFunction(buffer);
 // buffer shall be modified
}
func goFunction(cBuffer *C.char) {
  // how to modify 3-5?
  //strncpy(cBuffer+3, "XXX")
}

EDIT: to be more precise. I have to implement a callbackfunction, that accepts an outparameter, which I have to manipulate.

  void callback(char outbuffer[9]) {
    goFunction(outbuffer);
  }

as I understand Franks answer, I should do something like

  allocate new go buffer
  convert C buffer to go buffer
  manipulate go buffer
  allocate new C buffer
  convert go buffer to C buffer
  memcpy C buffer into outbuffer

That is too much allocation and conversion for my taste

question from:https://stackoverflow.com/questions/65934945/how-to-manipulate-a-c-character-array-inside-a-cgo-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See the documentation for Turning C arrays into Go slices to get a indexable go slice containing the C data.

Because you are modifying the C buffer data in place, using the Go slice as a proxy, you can simply pass the same buffer to the callback. Note that using append may allocate a new Go array for your slice, so you need to avoid it and make sure you have sufficient space available in the buffer beforehand.

func goFunction(cBuffer *C.char, length int) {
    slice := (*[1 << 28]C.char)(unsafe.Pointer(cBuffer))[:length:length]
    // slice can now be modified using Go syntax, without pointer arithmetic
    
    C.callback(cBuffer)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...