go编译.so文件在python中执行

简介: 在python中调用go代码

go代码

package main

import(
    "C"
)

func main(){}

// 上面都是固定的,需要其他包的话自行导入

// 定义函数,可定义多个,每个函数都要export
//export HelloWorld
func HelloWorld(info *C.char) *C.char {

    GoStr := C.GoString(info)
    GoStr += "123"

    return C.CString(GoStr)
}

编译

go build -buildmode=c-shared -o hello.so hello.go

编译后生成hello.so和hello.h,python中只需要so文件。

pythob中调用

# python3

import os
from ctypes import cdll, c_char_p

# 导包
lib = cdll.LoadLibrary(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'hello.so'))

# 获取函数
hello = lib.HelloWorld

hello.argtype = c_char_p
hello.restype = c_char_p

# 调用
print(hello(b"guido"))
目录
相关文章
|
11天前
|
IDE 开发工具 Python
python中SyntaxError: unexpected EOF while parsing(语法错误:解析时遇到意外的文件结束)
【5月更文挑战第14天】python中SyntaxError: unexpected EOF while parsing(语法错误:解析时遇到意外的文件结束)
38 6
|
1天前
|
Python Windows
一步步教你将包含其他文件的 Python 脚本等打包成 EXE
最近我编写了一个Python脚本,该脚本需要依赖两个同级目录下的文件才能正常运行。然而,当我将脚本打包成EXE程序后,必须将这两个文件放在EXE文件的同级目录下才能正常执行。为了简化部署,我希望能将这两个文件一起打包到EXE文件中,这时候该怎么办呢?
|
2天前
|
Python
Python文件的异常、模块与包
Python文件的异常、模块与包
9 3
|
2天前
|
存储 Python
Python文件编码概念详解
Python文件编码概念详解
11 1
|
3天前
|
Python
Python OS 文件/目录方法
Python OS 文件/目录方法
|
3天前
|
开发者 Python
Python File(文件) 方法
Python File(文件) 方法
|
3天前
|
安全 Python
Python 文件I
Python 文件I
|
4天前
|
Python
python语法中错误的文件或模块导入
【5月更文挑战第19天】
10 1
|
5天前
|
数据采集 数据挖掘 数据处理
Python数据分析实战:使用Pandas处理Excel文件
Python数据分析实战:使用Pandas处理Excel文件
74 0
|
8天前
|
Linux Python Windows
打包Python程序文件:pyinstaller实现
本文介绍基于Python语言中的pyinstaller模块,将写好的.py格式的Python代码及其所用到的所有第三方库打包,生成.exe格式的可执行文件,从而方便地在其他环境、其他电脑中直接执行这一可执行文件的方法。