Home >Backend Development >Golang >What is Golang Cgo

What is Golang Cgo

(*-*)浩
(*-*)浩Original
2019-12-03 09:20:034334browse

What is Golang Cgo

CGO provides a mechanism for golang and C language to call each other. Some third-party libraries may only have C/C implementation, and the implementation using pure golang may be a huge project. At this time, CGO comes in handy.                   (Recommended learning: go)

You can call the C interface in golang through CGO. The C interface can be packaged in C and provided to golang for calling.

The called C code can be provided directly in source code form or packaged as a static library or dynamic library and linked at compile time. It is recommended to use static libraries, which facilitates code isolation. The compiled binary does not have dynamic library dependencies and is convenient for release. It is also in line with the philosophy of golang.

The specific tutorial on how to use CGO is not covered in this article. Here we mainly introduce some details to avoid pitfalls when using CGO.

Parameter passing

Basic numerical type

Golang’s basic numerical type memory model is the same as C language, which is continuous Several bytes (1 / 2 / 4 / 8 bytes).

So when passing a numerical type, you can directly convert golang's basic numerical type into the corresponding CGO type and then pass it to the C function call, and vice versa:

package main

/*
#include <stdint.h>

static int32_t add(int32_t a, int32_t b) {
    return a + b;
}
*/
import "C"
import "fmt"

func main() {
    var a, b int32 = 1, 2
    var c int32 = int32(C.add(C.int32_t(a), C.int32_t(b)))
    fmt.Println(c) // 3
}

The above is the detailed content of What is Golang Cgo. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn