Golang and C Interaction: CGO

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

1. It is simple to refer to the C code in go, introduce the standard C code with a comment before the import "C", and then use the pseudo-package of c.xxx to refer to the identifier of the C code space. It is important to note that import "C" is a pseudo package and cannot be defined as import (...) with other package pieces.

2. Reference C code in go must manually release the C code object. The release method is C.free (unsafe. Pointer (XXX)), which also requires C code to include # include <stdlib.h>

3. The following must be understood in depth:

(1) Cgo recognizes this comment above import "C" statement.

(2) Any lines starting with #cgo followed by a space character is removed; These become directives for CGO.

(3) The remaining lines is used as a header when compiling the C parts of the package.

------------------------------------

Popular Memory:

(1) CGO is able to recognize comments for the import "C" statement.

(2) #cgo行用作cgo指令

(3) Other lines used as C header files

Point (2) is critical! Easily lead to duplicate definitions.

Practical questions:

Code Snippet 1:

-------------------------------

Package Main

/*

#include <stdlib.h>

#include "Prints.h"

*/

Import "C"

Import (

"FMT"

"Unsafe"

)

Func Main () {

Msg: = "This was a test for"

Cmsg: = c.cstring (msg)

Defer C.free (unsafe. Pointer (cmsg))

C.prints (CMSG)

Fmt. Println ("Done ...")

}

Introduce C code in the main package and use go run xxx.go to get an error. Go build--> to execute again, no error.

-------------------------------------

The solution above is to define wrapper to encapsulate the C code. For example:

Package Myc

/*

#include <stdlib.h>

#include "Prints.h"

*/

Import "C"

Import "unsafe"

Func cprints (msg string) {

Cmsg: = c.cstring (msg)

Defer C.free (unsafe. Pointer (cmsg))

C.prints (CMSG)

}

-------------------------------------------------

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.