用C语言为python写C扩展1

calc.c

#include <stdio.h> #include <Python.h> int add(int x, int y){ // C 函数 return x + y; } static PyObject *calc_add(PyObject *self, PyObject *args){ int x, y; // Python传入参数 // "ii" 表示传入参数为2个int型参数,将其解析到x, y变量中 if(!PyArg_ParseTuple(args, "ii", &x, &y)) return NULL; return PyLong_FromLong(add(x, y)); } // 模块的方法列表 static PyMethodDef CalcMethods[] = { {"add", calc_add, METH_VARARGS, "函数描述"}, {NULL, NULL, 0, NULL} }; // 模块 static struct PyModuleDef calcmodule = { PyModuleDef_HEAD_INIT, "calc", // 模块名 NULL, // 模块文档 -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ CalcMethods }; // 初始化 PyMODINIT_FUNC PyInit_calc(void) { return PyModule_Create(&calcmodule); }
setup.py

from distutils.core import setup, Extension

module1 = Extension('calc',
                    sources=['calc.c'])

setup(name='calc_model',
      version='1.0',
      description='Hello ?',
      ext_modules=[module1]
)
PS C:\Users\Desktop\my_file\pythonC> C:\python39\python.exe .\setup.py build
running build
running build_ext

用C写的python库现在已经安装成功,进入build下lib的文件夹里会看到一个.pyd的文件

 

 进入到.pyd文件所在目录,就可以成功导入我们用C写的python了.

PS C:\Users\Desktop\my_file\pythonC\build\lib.win-amd64-3.9> C:\python39\python.exe       
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> calc.add(7,9) 
16

如果你想在任何目录下都可以导入,就把这个.pyd copy到C:\python39\Lib\site-packages下即可.

参考: http://www.manongjc.com/detail/51-trghapdrxbmnqvh.html

 

posted @ 2022-11-14 14:25  腹肌猿  阅读(111)  评论(0编辑  收藏  举报