用C语言为python写C扩展2

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)

 

 

posted @ 2023-05-28 22:52  腹肌猿  阅读(29)  评论(0编辑  收藏  举报