修改Go代码中的C void*字节数组

huangapple go评论117阅读模式
英文:

Modifying a C void* byte array from Go code

问题

基本上,我正在尝试用Go函数替换C程序中的pread。我已经完成了大部分结构,但是我无法弄清楚如何用所需的字节填充缓冲区参数(buf unsafe.Pointer)。

daemon.c的一部分:

  1. static int preadShim(int fd, void *buf, size_t count, off_t offset) {
  2. //return pread(fd, buf, count, offset);
  3. return ReadOver(fd, buf, count, offset);
  4. }

在一个Golang文件中:

  1. package main
  2. import "C"
  3. import "fmt"
  4. import "unsafe"
  5. //export ReadOver
  6. func ReadOver(fd C.int, buf unsafe.Pointer, count C.int, offset C.int) C.int{
  7. fmt.Println("ReadOver被调用了")
  8. newBuf := []byte("注入的字节")
  9. //TODO: 将newBuf复制到buf中
  10. return count
  11. }

另一个Golang文件:

  1. package main
  2. // #include "daemon.c"
  3. import "C"
  4. import "fmt"
  5. func main() {
  6. //启动C程序
  7. C.start()
  8. }

有什么建议吗?我什么都没尝试过,也没有任何想法。

英文:

Basically, I'm trying to replace pread in a C program with a Go function. I've got most of the structure working, but I can't figure out how to populate the buffer argument (buf unsafe.Pointer) with the desired bytes.

Part of daemon.c:

  1. static int preadShim(int fd, void *buf, size_t count, off_t offset) {
  2. //return pread(fd, buf, count, offset);
  3. return ReadOver(fd, buf, count, offset);
  4. }

In a Golang file:

  1. package main
  2. import "C"
  3. import "fmt"
  4. import "unsafe"
  5. //export ReadOver
  6. func ReadOver(fd C.int, buf unsafe.Pointer, count C.int, offset C.int) C.int{
  7. fmt.Println("ReadOver got called")
  8. newBuf := []byte("injected bytes")
  9. //TODO: copy newBuf over buf
  10. return count
  11. }

Another Golang file:

  1. package main
  2. // #include "daemon.c"
  3. import "C"
  4. import "fmt"
  5. func main() {
  6. //Start C program
  7. C.start()
  8. }

Any suggestions? I've tried nothing and I'm all out of ideas.

答案1

得分: 2

你只需要从中创建自己的切片,例如:

  1. func ReadOver(fd C.int, buf unsafe.Pointer, count C.int, offset C.int) C.int {
  2. fmt.Println("ReadOver被调用了")
  3. newBuf := []byte("注入的字节")
  4. slice := &reflect.SliceHeader{Data: uintptr(buf), Len: int(count), Cap: int(count)}
  5. rbuf := *(*[]byte)(unsafe.Pointer(slice))
  6. return C.int(copy(rbuf, newBuf))
  7. }

这段代码是一个示例,它将创建一个新的切片并将其注入到给定的缓冲区中。函数的作用是将newBuf中的字节复制到rbuf中,并返回复制的字节数。

英文:

You just have to create your own slice from it, for example:

  1. func ReadOver(fd C.int, buf unsafe.Pointer, count C.int, offset C.int) C.int {
  2. fmt.Println("ReadOver got called")
  3. newBuf := []byte("injected bytes")
  4. slice := &reflect.SliceHeader{Data: uintptr(buf), Len: int(count), Cap: int(count)}
  5. rbuf := *(*[]byte)(unsafe.Pointer(slice))
  6. return C.int(copy(rbuf, newBuf))
  7. }

huangapple
  • 本文由 发表于 2014年9月11日 06:14:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/25775954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定