golang之cgo---類型轉換小試牛刀之C結構體和go結構體轉換

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

  上一篇文章講了go與C基本類型轉換(http://blog.csdn.net/freeape/article/details/51885308),但是在實際項目中用到的不僅僅是基本類型之間的轉換,更多的是函數封裝中的值傳遞和指標傳遞,如何在C功能函數中和Go中進行各種值和指標傳遞呢?根本方法還是利用基本類型,包括特別常用unsafe.Pointer

  先看一個例子:

package main/*#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")func main() {    var pDetectInfo unsafe.Pointer    C.setStruct(&pDetectInfo)    C.printStruct(pDetectInfo)    C.freeStruct(pDetectInfo)}

  從上面的例子可以知道還是利用了C和go的基本類型轉換,更多的是利用指標。得到的運行結果是:

A pDetectInfo address : 012832B0B pDetectInfo address : 012832B0id: 1score : 0.980pos.lt.x : 1.000pos.lt.y : 1.000pos.rd.x : 9.000pos.rd.y : 10.000C pDetectInfo address : 012832B0

  這是通過C的結構體將資料傳送給go,同樣的也可以利用在go中處理資料,然後傳遞給C,也是利用基本類型轉換。這裡做個記錄:

  • C中的結構體如果帶了typedef的話,那麼在go中定義C結構體就不需要帶struct了。反則反之。
  • Go中定義C結構體: var struct C.DetectFaceInfo
  • 再次注意,如果在結構體中有字元數組或者是char指標,注意區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.