go调用c代码示例
代码功能:
调用posix的共享内存接口,写入和读取共享内存数据;
代码:
package main /* #cgo LDFLAGS: -lrt #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> */ import "C" import "unsafe" import "fmt" import "os" func main() { name := C.CString("testshm") defer C.free(unsafe.Pointer(name)) fd, err := C.shm_open(name, C.int(C.O_RDWR|C.O_CREAT), 0) if err != nil { fmt.Println(err.Error()) } fmt.Printf("fd:%d", int(fd)) ret, err := C.ftruncate(fd, 1024*1024) if err != nil || ret != 0 { fmt.Println("truncate failed.") os.Exit(1) } strTest := `hello, test write to shared memory` content := C.CString(strTest) res, err := C.write(fd, unsafe.Pointer(content), C.size_t(len(strTest))) if err != nil || res == -1 { fmt.Println("write to shared memory failed.") os.Exit(1) } C.lseek(fd, 0, C.SEEK_SET) //pRead := make([]byte, 100) pRead := C.malloc(100) defer C.free(pRead) bytesRead, err := C.read(fd, unsafe.Pointer(pRead), 100) if err != nil { fmt.Println(err.Error()) os.Exit(1) } fmt.Printf("bytes read :%d, str are:%s", bytesRead, string(C.GoBytes(pRead, 100))) C.getchar() C.shm_unlink(name) }
3. 注意引入的头文件注释行与golang的import代码行直接必须无空行;
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。