This is a creation in Article, where the information may have evolved or changed.
In the previous article go与C基本类型转换
(http://blog.csdn.net/freeape/article/details/51885308), but in the actual project is not only used in the conversion between the basic types, More is the value passing and pointer passing in the function encapsulation, how to carry out various values and pointers in the C function and go? The fundamental approach is also to take advantage of basic types, including particularly commonunsafe.Pointer
Let's look at an example:
PackageMain/* #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define Max_ Faces_per_detect 64typedef struct point{float x; float y;} point;typedef struct rectangle{Point lt; Point Rd;} rectangle;typedef struct detectfaceinfo{int id; Float score; Rectangle POS;} Detectfaceinfo;void setstruct (void **ppdetectinfo) {detectfaceinfo *pdetectinfo = (Detectfaceinfo *) malloc (sizeof ( Detectfaceinfo)); memset (pdetectinfo, 0, sizeof (pdetectinfo)); Pdetectinfo->id = 1; Pdetectinfo->score = 0.98f; Pdetectinfo->pos.lt.x = 1; Pdetectinfo->pos.lt.y = 1; Pdetectinfo->pos.rd.x = 9; Pdetectinfo->pos.rd.y = 10; fprintf (stdout, "A pdetectinfo Address:%p\n", pdetectinfo); *ppdetectinfo = Pdetectinfo;} int printstruct (void *pdetectinfo) {Detectfaceinfo * Pdetectinfo = (Detectfaceinfo *) Pdetectinfo; fprintf (stdout, "B pdetectinfo Address:%p\n", pdetectinfo); fprintf (stdout, "ID:%d\n", PdeteCTINFO->ID); fprintf (stdout, "Score:%.3lf\n", Pdetectinfo->score); fprintf (stdout, "Pos.lt.x:%d\n", pdetectinfo->pos.lt.x); fprintf (stdout, "Pos.lt.y:%d\n", PDETECTINFO->POS.LT.Y); fprintf (stdout, "pos.rd.x:%d\n", pdetectinfo->pos.rd.x); fprintf (stdout, "POS.RD.Y:%d\n", PDETECTINFO->POS.RD.Y);} int freestruct (void *pdetectinfo) {fprintf (stdout, "C pdetectinfo Address:%p\n", pdetectinfo); Free ((detectfaceinfo*) pdetectinfo);} */Import "C"Import( _"FMT"_"Reflect" "unsafe")funcMain () {varPdetectinfo unsafe. Pointer c.setstruct (&pdetectinfo) c.printstruct (pdetectinfo) c.freestruct (Pdetectinfo)}
From the example above you can tell whether the basic type conversion of C and go is used, and more is the use of pointers. The resulting operation results are:
012832012832B0id:10.980pos.lt.x1.000pos.lt.y1.000pos.rd.x9.000pos.rd.y10.000012832B0
This is through the structure of C to the data to go, the same can also be used in go processing data, and then passed to C, but also take advantage of the basic type conversion. Here's a record:
If the struct in
- C has a typedef, then defining the C struct in go does not require a struct. The reverse is the opposite.
- go defines C struct: var struct c.detectfaceinfo
- Note again, if there is a character array or a char pointer in the struct, notice the difference