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

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

Modifying a C void* byte array from Go code

问题

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

daemon.c的一部分:

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

在一个Golang文件中:

package main

import "C"
import "fmt"
import "unsafe"

//export ReadOver
func ReadOver(fd C.int, buf unsafe.Pointer, count C.int, offset C.int) C.int{
    fmt.Println("ReadOver被调用了")
    newBuf := []byte("注入的字节")
    //TODO: 将newBuf复制到buf中
    return count
}

另一个Golang文件:

package main

// #include "daemon.c"
import "C"
import "fmt"

func main() {
    //启动C程序
    C.start()
}

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

英文:

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:

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

In a Golang file:

package main

import "C"
import "fmt"
import "unsafe"

//export ReadOver
func ReadOver(fd C.int, buf unsafe.Pointer, count C.int, offset C.int) C.int{
	fmt.Println("ReadOver got called")	
	newBuf := []byte("injected bytes")
	//TODO: copy newBuf over buf
	return count
}

Another Golang file:

package main

// #include "daemon.c"
import "C"
import "fmt"

func main() {
    //Start C program
    C.start()
}

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

答案1

得分: 2

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

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

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

英文:

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

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

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:

确定