Python调用go function
Python code foo.py
from ctypes import *
from ctypes import cdll
import time
class go_string(Structure):
_fields_ = [
("p", c_char_p),
("n", c_int)]
lib = cdll.LoadLibrary('/var/tmp/foo.so')
def bar(str):
b = go_string(c_char_p(bytes(str, "utf-8")), len(str))
lib.bar.restype = c_char_p
a = lib.bar(b, c_char_p(bytes(str, "utf-8")))
print(a)
bar("haha")
bar("hoho")
time.sleep(100)
Go code foo.go
package main
import (
"C"
"fmt"
"time"
)
//export bar
func bar(a string, b *C.char) *C.char {
c := a
d := C.GoString(b)
go func() {
for {
time.Sleep(time.Second)
fmt.Println("a:", a)
fmt.Println("b:", C.GoString(b))
fmt.Println("c:", c)
fmt.Println("d:", d)
}
}()
return C.CString("hello from go")
}
func main() {}
编译go
go build -buildmode=c-shared -o foo.so foo.go
编译生成的foo.h
/* Code generated by cmd/cgo; DO NOT EDIT. */
/* package command-line-arguments */
#line 1 "cgo-builtin-prolog"
#include <stddef.h> /* for ptrdiff_t below */
#ifndef GO_CGO_EXPORT_PROLOGUE_H
#define GO_CGO_EXPORT_PROLOGUE_H
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
#endif
/* Start of preamble from import "C" comments. */
/* End of preamble from import "C" comments. */
/* Start of boilerplate cgo prologue. */
#line 1 "cgo-gcc-export-header-prolog"
#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H
typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef GoUint64 GoUint;
typedef __SIZE_TYPE__ GoUintptr;
typedef float GoFloat32;
typedef double GoFloat64;
typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128;
/*
static assertion to make sure the file is being used on architecture
at least with matching size of GoInt.
*/
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
typedef _GoString_ GoString;
typedef void *GoMap;
typedef void *GoChan;
typedef struct { void *t; void *v; } GoInterface;
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
#endif
/* End of boilerplate cgo prologue. */
#ifdef __cplusplus
extern "C" {
#endif
extern char* bar(GoString p0, char* p1);
#ifdef __cplusplus
}
#endif
运行
Reference
- https://gist.github.com/helinwang/4f287a52efa4ab75424c01c65d77d939