Python calls the so library generated by Golang

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

Version: Go version go1.8.3 linux/amd64

The go language generated C language so library on the internet has a lot of information, because the project needs Python and go to combine, and Python can call the C language so library, so try a bit

Create a new test folder in the Gopath directory under SRC, and create a new test.go

Test.go Code

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

Using commands to generate libhello.so and libhello.h

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

Since the Hello function returns a gostring, the gostring declaration under Libhello.h is

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

Visible is a struct, so when using Python calls you need to use the cTYPES library to convert

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()

Output results

5Hellotest

Related Article

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.