用go语言给python3开发模块

实现方法概述

因为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 <Python.h>
    #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;
    }

编译命令:

  1. gcc -c -I/usr/include/python3.6m -fpic topy.c
  2. 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。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • TITLE: 编程语言乱炖 码农最大的烦恼——编程语言太多。不是我不学习,这世界变化快! 有时候还是蛮怀念十几、二...
    码园老农阅读 5,444评论 2 35
  • 我相遇而我存在。 即,我是风,我是雨,我是万物,万物是我; 我是时间,我是历史,我是众生,我不动于永恒。这样的稳定...
    田凯心理阅读 480评论 2 4
  • 减脂如何吃你是问到点子上了,因为大多数人主要关注的还是运动,殊不知吃对于减脂也是非常重要的! 首先一天几餐好呢? ...
    董海兰呀阅读 654评论 0 0
  • 人生而有时,生活,就是一面镜子,有好坏两面,好坏,都掌握在自己手中,只要心存善念,一切都是缘,姻缘,掌握在自己手中...
    王玉笙阅读 84评论 0 0
  • 文/陈幼南 梦里的家乡 草长莺飞 鸡鸣狗吠 山水田园 不知是谁一步步把我推进了城市 家,渐行渐远 而孩提时光 总是...
    陈幼南阅读 261评论 0 0