python調用golang產生的so庫

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

版本:go version go1.8.3 linux/amd64

go語言產生c語言的so庫在網上已經很多資料了,由於項目需要python和go結合,而python又可以調用c語言的so庫,所以嘗試了一下

在GOPATH目錄的src下建立一個test的檔案夾,裡面建立一個test.go

test.go代碼

package mainimport "C"//export Hellofunc Hello() string {    return "Hello"}//export Testfunc Test(){    println("test");}func main() {}

使用命令產生libhello.so和libhello.h

go build -x -v -ldflags "-s -w" -buildmode=c-shared  -o libhello.so test

由於Hello函數返回的是一個GoString,而GoString在libhello.h下的聲明是

typedef struct { const char *p; GoInt n; } GoString;

可見是一個結構體,所以使用python調用的時候需要使用ctypes庫轉換一下 

from ctypes import *    class StructPointer(Structure):      _fields_ = [("p", c_char_p), ("n", c_longlong)]    if __name__ == "__main__":      lib = cdll.LoadLibrary("./libhello.so")      lib.Hello.restype = StructPointer    str = lib.Hello()      print(str.n)    #str.n是GoString返回字元的長度,沒有截取的話後面會跟著一大串字串    print(str.p[:str.n])    lib.Test()

輸出結果 

5Hellotest

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.