How to use the C interface of the Golang call

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

2014-06-10 WCDJ


absrtact : This article mainly introduces how to implement Call C interface in Golang. Because Go's official website is often the wall, causes unable to browse the official detailed document, occasionally in browses Golang the source code to find some about the CGO usage, the concrete path in the Go/misc/cgo directory.


For example, in the Go/misc/cgo/gmp/gmp.go file, you can find ways to refer to the C library in Golang:

An example of wrapping a C library in Go. This is the GNU multiprecision Library GMP's integer type mpz_t wrapped to look like the Go package big ' s integer type Int .


The following is a simple example: hello.go

The complete code can be viewed here: https://github.com/gerryyang/goinaction/blob/master/src/cgo/src/hello.go

Package main/* #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include ". /inc/hello.h "//intentionally write the same ldflags DIFFERENTLY#CGO Linux ldflags:-L. /lib-lhello#cgo Darwin Ldflags:-L. /lib-lhello#if 0void Hello (const char *name) {printf ("%s\n", name); return;} #endif */import "C" Import ("FMT" "Time") func Hello (s string) {cs: = c.cstring (s) C.hello (CS)}func Main () {Seed (+) fmt. PRINTLN (int (c.random ())) time. Sleep (time. Duration (1) * time. Second) fmt. PRINTLN (int (c.random ())) Fmt. Println ("Getpid:", int (C.getpid ())) C.puts (C.cstring ("Call C-puts")) Hello ("Call C ' s go wrapper func") C.hello (c.cstring ("Call C Hello func")} Func Seed (i int) {c.srandom (C.uint (i))}


Reference

[1] http://www.cnblogs.com/yjf512/archive/2012/07/19/2599304.html

[2] http://tonybai.com/tag/cgo/




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.