首页 > 编程语言 >用C语言为python写C扩展2

用C语言为python写C扩展2

时间:2023-05-28 23:14:36浏览次数:58  
标签:Files amd64 spam python win 扩展 C语言 build egg

spammodule.c

#include <Python.h>

static PyObject * spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;
    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return PyLong_FromLong(sts);
}


static PyMethodDef SpamMethods[] = {

    {"system",  spam_system, METH_VARARGS,
     "Execute a shell command."},

    {NULL, NULL, 0, NULL}        /* Sentinel */
};

static struct PyModuleDef spammodule = {
   PyModuleDef_HEAD_INIT,
   "spam",   /* name of module */
   NULL, /* module documentation, may be NULL */
   -1,       /* size of per-interpreter state of the module,
                or -1 if the module keeps state in global variables. */
   SpamMethods
};


PyMODINIT_FUNC PyInit_spam(void)
{
    return PyModule_Create(&spammodule);
}
View Code

setup.py

from setuptools import setup, Extension, distutils, Command, find_packages

C = Extension("spam",
              # libraries=main_libraries,
              sources=['spammodule.c'],
              language='c',
              )

setup(name="spam",
      version=1.0,
      ext_modules=[C],
      )
View Code

生成并安装C扩展

python setup.py build
python setup.py install


C:\Python38\python.exe .\setup.py build
running build
    C:\Python38\python.exe .\setup.py build
    running build
    running build_ext
    building 'spam' extension
    "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.36.32532\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Python38\i
    nclude -IC:\Python38\Include "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.36.32532\include" "-IC:\Program Files\Microsoft Visua
    l Studio\2022\Community\VC\Tools\MSVC\14.36.32532\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include" "-IC:\Pr
    ogram Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Wi
    ndows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10
    \\include\10.0.22000.0\\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /Tcspammodule.c /Fobuild\temp.win-amd64-cpython-38\Release\s
    spammodule.c
    creating C:\Users\23798\Desktop\Python_project\extend_wtih_C\build\lib.win-amd64-cpython-38
    "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.36.32532\bin\HostX86\x64\link.exe" /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBE
    D,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Python38\libs /LIBPATH:C:\Python38 /LIBPATH:C:\Python38\PCbuild\amd64 "/LIBPATH:C:\Program Files\Microsoft Visual Studio\20
    22\Community\VC\Tools\MSVC\14.36.32532\ATLMFC\lib\x64" "/LIBPATH:C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.36.32532\lib\x64" "/
    LIBPATH:C:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\lib\um\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.22000.0\ucrt\x64" "/LIBPATH:C:\
    Program Files (x86)\Windows Kits\10\\lib\10.0.22000.0\\um\x64" /EXPORT:PyInit_spam build\temp.win-amd64-cpython-38\Release\spammodule.obj /OUT:build\lib.win-a
    md64-cpython-38\spam.cp38-win_amd64.pyd /IMPLIB:build\temp.win-amd64-cpython-38\Release\spam.cp38-win_amd64.lib
      正在创建库 build\temp.win-amd64-cpython-38\Release\spam.cp38-win_amd64.lib 和对象 build\temp.win-amd64-cpython-38\Release\spam.cp38-win_amd64.exp
    正在生成代码
    已完成代码的生成

C:\Python38\python.exe .\setup.py install
    C:\Python38\python.exe .\setup.py install
    running install
    C:\Python38\lib\site-packages\setuptools\_distutils\cmd.py:66: SetuptoolsDeprecationWarning: setup.py install is deprecated.
    !!

            ********************************************************************************
            Please avoid running ``setup.py`` directly.
            Instead, use pypa/build, pypa/installer, pypa/build or
            other standards-based tools.

            See https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html for details.
            ********************************************************************************

    !!
      self.initialize_options()
    C:\Python38\lib\site-packages\setuptools\_distutils\cmd.py:66: EasyInstallDeprecationWarning: easy_install command is deprecated.
    !!

            ********************************************************************************
            Please avoid running ``setup.py`` and ``easy_install``.
            Instead, use pypa/build, pypa/installer, pypa/build or
            other standards-based tools.

            See https://github.com/pypa/setuptools/issues/917 for details.
            ********************************************************************************

    !!
      self.initialize_options()
    running bdist_egg
    running egg_info
    creating spam.egg-info
    writing spam.egg-info\PKG-INFO
    writing dependency_links to spam.egg-info\dependency_links.txt
    writing top-level names to spam.egg-info\top_level.txt
    writing manifest file 'spam.egg-info\SOURCES.txt'
    reading manifest file 'spam.egg-info\SOURCES.txt'
    writing manifest file 'spam.egg-info\SOURCES.txt'
    installing library code to build\bdist.win-amd64\egg
    running install_lib
    running build_ext
    creating build\bdist.win-amd64
    creating build\bdist.win-amd64\egg
    copying build\lib.win-amd64-cpython-38\spam.cp38-win_amd64.pyd -> build\bdist.win-amd64\egg
    creating stub loader for spam.cp38-win_amd64.pyd
    byte-compiling build\bdist.win-amd64\egg\spam.py to spam.cpython-38.pyc
    creating build\bdist.win-amd64\egg\EGG-INFO
    copying spam.egg-info\PKG-INFO -> build\bdist.win-amd64\egg\EGG-INFO
    copying spam.egg-info\SOURCES.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying spam.egg-info\dependency_links.txt -> build\bdist.win-amd64\egg\EGG-INFO
    copying spam.egg-info\top_level.txt -> build\bdist.win-amd64\egg\EGG-INFO
    writing build\bdist.win-amd64\egg\EGG-INFO\native_libs.txt
    zip_safe flag not set; analyzing archive contents...
    __pycache__.spam.cpython-38: module references __file__
    creating dist
    creating 'dist\spam-1.0-py3.8-win-amd64.egg' and adding 'build\bdist.win-amd64\egg' to it
    removing 'build\bdist.win-amd64\egg' (and everything under it)
    Processing spam-1.0-py3.8-win-amd64.egg
    creating c:\python38\lib\site-packages\spam-1.0-py3.8-win-amd64.egg
    Extracting spam-1.0-py3.8-win-amd64.egg to c:\python38\lib\site-packages
    Adding spam 1.0 to easy-install.pth file

    Installed c:\python38\lib\site-packages\spam-1.0-py3.8-win-amd64.egg
    Processing dependencies for spam==1.0
    Finished processing dependencies for spam==1.0


C:\Python38\python.exe
    Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import spawn
    >>> spam.system("dir")
     驱动器 C 中的卷没有标签。
     卷的序列号是 7299-6435

C:\Python38\python.exe .\setup.py build 报错
running build_ext
building 'spam' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
https://wiki.python.org/moin/WindowsCompilers
https://c2rsetup.officeapps.live.com/c2r/downloadVS.aspx?sku=community&channel=Release&version=VS2022&source=VSLandingPage&add=Microsoft.VisualStudio.Workload.ManagedDesktop&add=Microsoft.VisualStudio.Workload.Azure&add=Microsoft.VisualStudio.Workload.NetWeb&includeRecommended=true&cid=2030:6386a4ced0f9418fafc83f85f93fe877
安装最新的visual studio即可
View Code

 文件结构如下

可以看到,编写的c扩展文件由4个部分组成, 分别是两个函数(PyObject,PyMODINIT_FUNC)和两个数组(PyModuleDef,PyMethodDef)

 

 

标签:Files,amd64,spam,python,win,扩展,C语言,build,egg
From: https://www.cnblogs.com/pfeiliu/p/17439077.html

相关文章

  • C语言编程—枚举
    枚举是C语言中的一种基本数据类型,用于定义一组具有离散值的常量。它可以让数据更简洁,更易读。枚举类型通常用于为程序中的一组相关的常量取名字,以便于程序的可读性和维护性。定义一个枚举类型,需要使用enum关键字,后面跟着枚举类型的名称,以及用大括号{}括起来的一组枚举常量。......
  • Python自动化运维
    2-27在命令行窗口中启动的Python解释器中实现在Python自带的IDLE中实现print("Helloworld")编码规范每个import语句只导入一个模块,尽量避免一次导入多个模块不要在行尾添加分号“:”,也不要用分号将两条命令放在同一行建议每行不超过80个字符使用必要的空行可以增加代码的可读性运......
  • Python学习
    3-13字符串类型字符串类型:str   1.定义格式:       变量='内容'           打印一行       变量="内容"           打印一行       变量='''内容'''或者三引号           可以通过回车的方式换行,且打印出......
  • Python中列表(List)元组(Tuple)集合(Set)的区别和适用场景
    在Python中,列表(List)和元组(Tuple)都是序列类型的数据结构。它们具有相似的特性,如可以通过下标访问元素、支持切片操作等。而集合(Set)则是一个无序的集合类型。下面是它们各自的特点和适用场景:列表(List):有序的序列类型。可以存储任意类型的对象,并且可以动态地修改元素。适用于需......
  • 初识C语言:从菜鸟变大牛(3)
    上篇我们讲解了变量、常量、字符串、转义字符、注释。那么我们继续来学习C语言的一些基本知识,同样,知识也是点到为止,不会很深入,后面我会发布更深层次的知识。(注:本篇的内容稍稍有点多,大家可以分批学习)1.选择语句在C语言中有时有多种分支,我们就需要用到选择语句在C语言中有两种常见的......
  • 常见项目——C语言实现2048小游戏(附源码和可执行文件)
    1.实现效果展示1.1界面图片说明:进入下面各页面后均可通过按键“q”来退出。1)菜单页2)开始游戏页3)游戏规则页4)按键说明页5)退出游戏页1.2视频展现戳此处查看视频演示1.3游戏源码及可执行文件(exe)下载支持作者,请关注公众号“优秀物联人”回复“2048小游戏”获取下......
  • Python 使用ConfigParser操作ini配置文件
    ini配置文件格式如下要求:ini文件必须是GBK编码,如果是UTF-8编码,python读取配置文件会报错。#这里是注释内容#[FY12361]#妇幼保健接口服务端口serverIP=192.168.1.11serverPort=8400[SM]#国产SM加密服务端口serverIP=192.168.1.11serverPort=8500说明:1.注释内容......
  • C语言进阶--#和##运算符
    ##运算符用于在预处理器粘连两个标识符##的连接作用实在预处理期完成的,因此只在宏定义中有效编译器不知道##的连接作用用法:#defineBB(a,b)a##bintBB(a,1);  //inta1;a1=2; #运算符用于预处理期将宏参数转换为字符串#的转换作用是在预处理期完成的,因此只在宏......
  • python老男孩第四课
    本节内容 反射之第二   装饰器   面向对象编程  异常处理  断言  反射之第二通过import导入 可以理解为导入文件夹  getattr 导入文件或函数装饰器defoutt(func):defwapper(arg):print('你好')reslt=func(arg)......
  • C语言进阶--#pragma pack
    为什么需要内存对齐?--CPU对内存的读取不是连续的,而是分成块读取的,块的大小只能是1、2、4、16、。。。字节--当读取操作的数据未对齐,则需要两次总线周期来访问内存,因此性能会大打折扣--某些硬件平台只能从规定的相对地址处读取特定类型的数据,否则产生硬件异常#pragmapack用于......