前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用C语言编写Python扩展包

使用C语言编写Python扩展包

作者头像
lpe234
发布2020-07-27 17:27:07
2.2K0
发布2020-07-27 17:27:07
举报
文章被收录于专栏:若是烟花若是烟花

使用C编写Python扩展包。官网文档其实已经很详尽~ 使用场景猜想:某些需要高效处理的算法、某些耗时的操作优化、或者某些核心算法加密等~

环境:macOS + pyhton3.7

文档地址:

整体结构

➜  strings_pkg git:(master) tree   
.
├── LICENSE
├── README.md
├── setup.py
└── strings_pkg
    ├── __init__.py
    └── strings.c

1 directory, 5 files

扩展模块 strings.c

//
// Created by lpe234 on 2018/12/27.
//
// doc: https://docs.python.org/3/extending/extending.html

#include <Python.h>


/**
 * reverse
 * 实际执行函数
 *
 * @param str
 * @param size
 */
void reverse(char *str, int size) {
    for (int i = 0, j = size-1; i < j ; ++i, --j) {
        char tmp = str[i];
        str[i] = str[j];
        str[j] = tmp;
    }
}

/**
 * 对函数进行封装
 *
 * @param self
 * @param args
 * @return
 */
PyObject *
strings_reverse(PyObject *self, PyObject *args) {
    char *str;

    // 参数解析
    if (!PyArg_ParseTuple(args, "s", &str)) {
        return NULL;
    }

    // 调用 reverse
    reverse(str, (int) strlen(str));

    return Py_BuildValue("s", str);
}

/**
 * 定义模块方法表
 *
 */
static PyMethodDef StringsMethods[] = {
        {"reverse", strings_reverse, METH_VARARGS, "Reverse str."},
        {NULL, NULL, 0, NULL}
};

/**
 * 定义模块
 *
 */
static struct PyModuleDef stringsmodule = {
        PyModuleDef_HEAD_INIT,
        "strings",
        "reverse str, \"abc\" => \"cba\"",
        -1,
        StringsMethods
};

/**
 * 模块初始化
 *
 * @return
 */
PyMODINIT_FUNC
PyInit_strings(void) {
    return PyModule_Create(&stringsmodule);
}

安装模块 setup.py

import setuptools

with open('README.md', 'r') as fh:
    long_description = fh.read()

strings_module = setuptools.Extension('strings',
                           sources=['strings_pkg/strings.c'],
                           language='c')

setuptools.setup(
    name="strings_pkg",
    version="0.0.1",
    author="lpe234",
    author_email="lpe234@qq.com",
    description="string extension package",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/lpe234/strings_pkg",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    ext_modules=[strings_module]
)

上传至pypi仓库

➜ twine upload dist/*

体验

➜  ~ pip3 install strings-pkg
Collecting strings-pkg
  Downloading https://files.pythonhosted.org/packages/f9/30/d9324783ef220de473b8fac550029c43ef2a8b7c26a16a3881ae6c8d006a/strings_pkg-0.0.1-cp37-cp37m-macosx_10_14_x86_64.whl
Installing collected packages: strings-pkg
Successfully installed strings-pkg-0.0.1
➜  ~ python3
Python 3.7.1 (default, Nov 28 2018, 11:51:47)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import strings
>>> strings.reverse('hello world')
'dlrow olleh'
>>>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 整体结构
  • 扩展模块 strings.c
  • 安装模块 setup.py
  • 上传至pypi仓库
  • 体验
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档