使用C语言编写Python扩展包

原创
2018/12/27 18:14
阅读数 172

使用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'
>>>
展开阅读全文
打赏
0
3 收藏
分享
加载中
更多评论
打赏
0 评论
3 收藏
0
分享
返回顶部
顶部