go语言调用python_用go语言给python3开发模块

本文介绍了如何使用Go语言编写函数,编译成C静态库,然后通过C包装为Python3模块,最后编译为动态库供Python调用。以一个线程乱序打印字符串的示例详细阐述了整个过程,展示了Go语言在网络编程和多线程方面的优势。
摘要由CSDN通过智能技术生成

实现方法概述

因为go语言可以生成gcc可用的静态库,我们可以用go语言实现我们需要的功能,然后编译成静态库,再用C语言调用该静态库,包装成python3模块,然后编译成动态库供python3调用。

实例

下面用一个用go线程乱序打印五次字符串参数的函数作为示例。

go程序

文件名:tryme.go

代码:

package main

import (

"fmt"

"math/rand"

"sync"

"time"

)

import "C"

func runp(wg *sync.WaitGroup, str string) {

defer wg.Done()

t := rand.Intn(5)

time.Sleep(time.Second * time.Duration(t))

fmt.Println(str)

}

//export Tryme

func Tryme(str string) {

var wg sync.WaitGroup

for i := 1; i <= 5; i++ {

wg.Add(1)

go runp(&wg, fmt.Sprintf("%v %v", i, str))

}

wg.Wait()

}

func main() {}

编译命令:

go build -o tryme.a -ldflags="-s -w" -buildmode=c-archive tryme.go

结果会生成2个文件:

tryme.a

tryme.h

C包装程序

文件名:topy.c

代码:

#include

#include "tryme.h"

#include "string.h"

void trythis(char *s){

GoString gs = {s,strlen(s)};

Tryme(gs);

}

//add wrapped function

static PyObject* wrap_trythis(PyObject *self, PyObject *args)

{

//Convert the python input objects into C objects

char *s;

if(!PyArg_ParseTuple(args, "s", &s)){

return NULL;

}

//Call c function

trythis(s);

//wrap the result from c function to python object.

return (PyObject*)Py_BuildValue("");

}

//define the PyMethodDef methods

static PyMethodDef wrap_methods[] ={

{"trythis", (PyCFunction)wrap_trythis, METH_VARARGS,NULL},

{NULL, NULL}

};

struct module_state {

PyObject *error;

};

static struct PyModuleDef moduledef = {

PyModuleDef_HEAD_INIT,

"topy",

NULL,

sizeof(struct module_state),

wrap_methods,

NULL,

NULL,

NULL,

NULL

};

//initilization function

PyMODINIT_FUNC PyInit_topy(void)

{

PyObject *module = PyModule_Create(&moduledef);

return module;

}

编译命令:

gcc -c -I/usr/include/python3.6m -fpic topy.c

gcc -o topy.so -shared -lpthread topy.o tryme.a

结果生成动态库: topy.so

用python3调用topy库

代码:

import topy

topy.trythis("hello boy.")

结果输出(顺序随机):

4 hello boy.

5 hello boy.

2 hello boy.

1 hello boy.

3 hello boy.

结语

在网络编程、多线程编程等方面,go语言有这极大的优越性,非常适合用来扩展python3。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值