Go Call C code example

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
    1. Code Features:

      Invokes a POSIX shared memory interface to write and read shared memory data;

    2. Code:

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 (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. Note that the imported header file Comment line and the import code line of the Golang must have no blank line directly;


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.