windows下使用Python调用Golang编译的动态链接库
一、编写golang开发的共享模块
libdemo.go
//libdemo.go
package main
import (
"C"
"fmt"
)
//export Foo
func Foo(a, b int) int {
return a + b
}
//export Bar
func Bar(s *C.char) {
fmt.Println("Hello, ", C.GoString(s))
}
func main() {
Bar(C.CString("demo你好"))
}
执行命令构建模块
go build -o libdemo.dll -buildmode=c-shared main.go
二、python中调用模块
golang_libdemo.py
from ctypes import * libdemo = cdll.LoadLibrary(r'C:\workspaces\goWorks\libdemo\libdemo.dll') print(libdemo.Foo(1,2)) print(libdemo.Bar(c_char_p('你好'.encode())))
执行结果:
3
Hello, 你好
0
关联阅读:
Go build模式之c-archive,c-shared,linkshared
https://davidchan0519.github.io/2019/04/05/go-buildmode-c/
golang和python互相调用
https://www.cnblogs.com/dhcn/p/12044521.html
Windows 下 Python3.6 调用GCC C 动态库例子
Windows 下GCC编译C程序调用Golang静态库和C动态库
三、Python与C类型映射
https://docs.python.org/3.8/library/ctypes.html#ctypes.c_char
ctypes
defines a number of primitive C compatible data types:
ctypes type | C type | Python type |
---|---|---|
c_bool |
_Bool |
bool (1) |
c_char |
char |
1-character bytes object |
c_wchar |
wchar_t |
1-character string |
c_byte |
char |
int |
c_ubyte |
unsigned char |
int |
c_short |
short |
int |
c_ushort |
unsigned short |
int |
c_int |
int |
int |
c_uint |
unsigned int |
int |
c_long |
long |
int |
c_ulong |
unsigned long |
int |
c_longlong |
__int64 or long long |
int |
c_ulonglong |
unsigned __int64 or unsigned long long |
int |
c_size_t |
size_t |
int |
c_ssize_t |
ssize_t or Py_ssize_t |
int |
c_float |
float |
float |
c_double |
double |
float |
c_longdouble |
long double |
float |
c_char_p |
char * (NUL terminated) |
bytes object or None |
c_wchar_p |
wchar_t * (NUL terminated) |
string or None |
c_void_p |
void * |
int or None |
golang和python之间,当前可以通过golang的cgo和python的ctypes,把golang对象和python对象分别转换为C对象,从而通过编译和调用c的动态连接库,完成交互。
发布时间:2022-01-09 19:48:47
关键词:python,golang
浏览量:0