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)
}
-------------------------------------------------