This is a creation in Article, where the information may have evolved or changed. The following is reproduced from: http://chaishushan.blog.163.com/blog/static/1301928972012799345127/
Author: chai2010 <chaishushan{AT}gmail.com> Copyright: Reprint Please declare the original author
The go language currently has 2 compilers: GC and GCCGO. Where GC provides CGO support for the C language, and GCCGO support C + +. In addition, Swig provides support for the go language after 2.0.1, and supports C + + classes and callbacks. Go official provide cmd/go command, can well support Cgo,swig support is still in perfect.
This article provides a brief introduction to the CGO-based integrated/C + + library for the platform: linux/windows.
1. Hello, World
Hello.gopackage Main
Import "FMT"
Func Main () { Fmt. Printf ("Hello, World \ n")}
Because go compiles quickly and Cmd/go supports remote get third-party libraries, go can be easily used as a scripting language. Running the above program, you can enter directly: Go Run hello.go.
2. CGO-based Hello, the world
Package Main
/* #include <stdio.h>*/import "C"
Func Main () { C.puts (C.cstring ("Hello, World \ n"))}
In the import "C" before comments can be imported C functions/variables/macros wait for a virtual "C" package. We can access the functions in C directly using the C. prefix.
In the current example, use C's puts function to output "Hello, World". The reason for not using the C-language classic printf function is that the parameters of printf are mutable, and CGO does not support the functions that access your mutable parameters.
If you need to use the printf function, you need to do the wrapper again.
3. The C-language printf-based Hello, the world
Package Main
/* #include <stdio.h>
static void Myprint (const char* msg) { printf ("Myprint:%s", msg);} */import "C"
Func Main () { C.puts (C.cstring ("Hello, World \ n")) c.printf (C.cstring ("Hello, World \ n")) Error C.myprint (C.cstring ("Hello, World \ n"))}
We use Myprint to mask the variable parameter characteristics of printf. Functions defined in the import "C" are generally recommended to be defined as static.
4. Functions commonly used by CGO
CGO has built in some common functions:
Go string to C string//the C string was allocated in the C heap using malloc.//It's the caller ' s responsibility to AR Range for it to be//freed, such as by calling C.free.func c.cstring (string) *c.char
C string to Go stringfunc c.gostring (*c.char) string
C string, length to Go stringfunc c.gostringn (*c.char, C.int) string
C pointer, length to Go []bytefunc c.gobytes (unsafe. Pointer, c.int) []byte
Our previous example is the use of c.cstring to convert the string of go to the char* type of the C language. The space returned by c.cstring is allocated by malloc in the C language and needs to be freed after use.
5. Releasing space allocated by c.cstring
Package Main
/* #include <stdio.h> #include <stdlib.h>*/import "C" import "unsafe"
Func Main () { CSTR: = c.cstring ("Hello, World \ n") Defer C.free (unsafe. Pointer (CSTR)) C.puts (C.cstring ("Hello, World \ n"))}
C.cstring returns the char* type of the C language, corresponding to the *c.char of the Go language. The free parameter of the C language is the void* type, which corresponds to the unsafe of the go language. Pointer. Because the Go language prohibits 2 different types of implicit conversions, it is necessary to manually convert the type when using C.free, corresponding to code unsafe. Pointer (CSTR). In this way, there is no memory leak in the CStr space.
In addition, when using CGO, the "unsafe" package is generally imported. Some of the underlying tools in the C language are provided in "unsafe":
Func Alignof (v arbitrarytype) Uintptrfunc Offsetof (v arbitrarytype) Uintptrfunc Sizeof (v arbitrarytype) uintptrtype Arbitrarytypetype Pointer
6. Common C/go Type conversions
When using CGO, the basic data type conversion between C and go is an issue that is frequently encountered.
Integer/floating-point conversion:
C-goi_go = Int (c.i_c) F32_fo = float32 (c.float_c) F64_fo = float64 (C.double_c)
Go-Ci_c = C.int (i_go) Float_c = C.float (f32_go) Double_c = c.double (F64_go)
String Conversions:
C-Gostr_go = c.gostring (c.str_c)
Go-cstr_c = c.cstring (Str_go)
Pointer conversion://C-gop_int_go = (*int) (unsafe. Pointer (C.p_int))//Go-and Cp_int_c = (*c.int) (unsafe. Pointer (&myintslice[0]))
For example, to invoke the C language's main function (the code cannot run, just to illustrate the string array conversion):
Func callmain (args []string) int { ARGC: = C.int (len (args)) ARGV: = Make ([]*c.char, Len (args)) For I: = 0; I < Len (args); i++ { Argv[i] = c.cstring (Args[i]) } RV: = C.main (argc, (**c.char) (unsafe. Pointer (&ARGV))) return int (RV)}
If it is a callback function, it needs to be encapsulated in C (rather cumbersome).
7. Connection options
You can use the #cgo extension preprocessing command to specify Cflags/ldflags.
For example, the connection parameters of the Go-gdal Library are:/* #include "go_gdal.h"
#cgo Linux pkg-config:gdal#cgo Darwin pkg-config:gdal#cgo Windows Ldflags:-lgdal.dll*/import "C"
#cgo之后可以跟系统命令, specify the system that the parameter corresponds to in effect. For Linux and other systems, you can use Pkg-config directly.
8. Integrated C + + library
Currently CGO does not recognize C + + syntax. If you need to use a C + + library, you can encapsulate the API for C + + libraries in the form of a language, and then compile it as a dynamic library. Based on the dynamic library generated for the export Lib and a header file with only the C API description, then you can import the go environment using.
Note: CGO content is more miscellaneous, and need to build a complete development environment, now finishing a little, later slowly add. At present, the author has tried 2 C library of Go help set, the reader can refer to. The URL is:
http://code.google.com/p/go-gdal/http://code.google.com/p/go-opencv/
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.