Golang CGO A---Go and c basic type conversion

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

In embedded development, there is always a need to deal with C + +, and in development there are always some requirements to use some other tools, such as the Go language.

The go language is optimized for programming multi-processor system applications, with go-compiled programs that are comparable to C or C + + code, and are more secure and support parallel processes.
The grammar of the Go language is close to the C language, but the declaration of the variable is different, and the other syntax differs in that the for loop and if judgment statements do not need to be enclosed in parentheses. The go language supports the garbage collection feature.
In contrast to C + +, the Go language does not include features such as exception handling, inheritance, generics, assertions, virtual functions, but adds language-level support for slice, concurrency, pipelines, garbage collection, Interface (interface), and more.

  

The branch of the compiler that currently has two go languages. Official compiler GC and GCCGO. Official compilers support cross-platform compilation (but 不支持CGO )

Go can also 嵌入 C code, but can not embed C + + code, of course, you can call the C + + API in some way (such as Swig), this article mainly talk about CGO. How to embed C or call the dynamic library is simply skipped, the main note:

    • You can use annotations // and /**/ surround C code
    • There is no blank line between the import "C" and the containing C code
    • The import and compilation options for dynamic libraries are set by Ldflags, Cflags/cxxflags
    • You can also use Pkg-config#cgo pkg-config : xxxxname
    • The Compile macro definition specifies#cgo CFLAGS: -DNDEBUG -DXXXX=2

Let's look at the type conversion between go and C today:

Char--C.Char-bytesigned Char--C.schar-int8unsigned Char--C.uchar-uint8 Short int--C. Short-Int16 Short unsigned int--C.ushort-UInt16int--C.int-intunsigned int--C.uint-UInt32Long int--C.Long-Int32 or Int64Long unsigned int--C.ulong-UInt32 or UInt64Long Long int--C.longlong-Int64Long Long unsigned int--C.ulonglong-UInt64float--C.float-Float32Double--C.Double-Float64wchar_t--C.wchar_t-void*, unsafe. Pointer

Programming Test:

 PackageMain/ * #include <stdio.h> #include <stdlib.h>char ch = ' M '; unsigned char uch = 253;short St = 233;int i = 257;lo ng LT = 11112222;float F = 3.14;double db = 3.15;void * P;char *str = "Const string"; char str1[64] = "char array"; void pri NtI (void *i) {printf ("Print i =%d\n", (* (int *) i));}    struct Imginfo {char *imgpath;    int format;    unsigned int width; unsigned int height;};        void Printstruct (struct imginfo *imginfo) {if (!imginfo) {fprintf (stderr, "Imginfo is null\n");    return;    } fprintf (stdout, "Imgpath =%s\n", Imginfo->imgpath);    fprintf (stdout, "format =%d\n", Imginfo->format); fprintf (stdout, "width =%d\n", imginfo->width);} */Import "C"Import("FMT"    "Reflect"    "unsafe")funcMain () {FMT. Println ("----------------Go to C---------------") FMT. Println (C.char (' Y ') FMT. Printf ("%c\n", C.char (' Y ') FMT. Println (C.uchar (' C ') FMT. Println (C.short(254) FMT. Println (C.long(11112222))varGoiint=2    //unsafe. Pointer to void *CPI: = unsafe. Pointer (&goi) C.printi (CPI) FMT. Println ("----------------C to Go---------------") FMT. Println (c.ch) fmt. Println (C.uch) fmt. Println (C.st) fmt. Println (C.I.) fmt. Println (c.lt) F: =float32(C.F) fmt. Println (reflect. TypeOf (f)) fmt. PRINTLN (C.F) DB: =float64(c.db) fmt. Println (reflect. TYPEOF (db)) FMT. Println (c.db)//Distinguish constant string from char array, convert to go type differentstr: = c.gostring (C.STR) fmt. Println (str) FMT. Println (reflect. TypeOf (C.STR1))varCharray []byte     forI: =RangeC.STR1 {ifC.str1[i]! =0{Charray =Append(Charray,byte(C.str1[i])) }} FMT. Println (Charray) fmt. Println (string(Charray)) forI: =0; I <Ten; i++ {imginfo: = c.struct_imginfo{imgpath:c.cstring (".. /images/xx.jpg "), Format:0, Width: -, Height: -}deferC.free (unsafe. Pointer (Imginfo.imgpath)) c.printstruct (&imginfo)} fmt. Println ("----------------C Print----------------")}

Output Result:

----------------Go to C---------------89Y6725411112222----------------C to Go---------------7725323325711112222float323.14float643.15const string[64]main._Ctype_char[99 104 97 114 32 97 114 114 97 121]char array----------------C Print----------------print i = 2imgPath = ../images/xx.jpgformat = 0width = 500imgPath = ../images/xx.jpgformat = 0width = 500imgPath = ../images/xx.jpgformat = 0width = 500imgPath = ../images/xx.jpgformat = 0width = 500
总结

In the basic type, the type conversion between C and go is still relatively convenient. But distinguishing between strings and character arrays is a different type. There is a very important conversion:void * -> unsafe.Pointer

https://golang.org/cmd/cgo/
Https://zh.wikipedia.org/wiki/Go#cite_note-6

Related Article

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.