如何使用ASM代码为Python构建C库



我正在使用" python.h"构建一个用于python的C库,我巧妙地制作了一个用于添加两个数字,build-it和install-it。但是现在我想使用C中的内联ASM代码添加这些数字。但是,当我使用我的设置构建C文件时,它会给我一个错误。有人做过这样的事情并可能有解决方案吗?还是您还有其他想法。

这是我的 hectorasmmodule.c

#include <Python.h>
#include <stdio.h>
static PyObject *hectorASM_ADD(PyObject *self, PyObject *args) {
    int num1, num2;
    if (!PyArg_ParseTuple(args, "ii", &num1, &num2)) {
        return NULL;
    }
    // int res = num1 + num2;
    int res = 0;
    __asm__("add %%ebx, %%eax;" : "=a"(res) : "a"(num1), "b"(num2));
    return Py_BuildValue("i", res);
}
static PyMethodDef hectorASM_methods[] = {
    // "PythonName"     C-function Name     argument presentation       description
    {"ADD", hectorASM_ADD, METH_VARARGS, "Add two integers"},
    {NULL, NULL, 0, NULL}   /* Sentinel */
};
static PyModuleDef hectorASM_module = {
    PyModuleDef_HEAD_INIT,
    "hectorASM",                       
    "My own ASM functions for python",
    0,
    hectorASM_methods                 
};
PyMODINIT_FUNC PyInit_hectorASM() {
    return PyModule_Create(&hectorASM_module);
}

这是我的 setup.py

from distutils.core import setup, Extension, DEBUG
module1 = Extension(
    'hectorASM',
    sources = ['hectorASMmodule.c']
)
setup (
    name = 'hectorASM',
    version = '1.0',
    description = 'My own ASM functions for python',
    author = 'hectorrdz98',
    url = 'http://sasukector.com',
    ext_modules = [module1]
)

这是我运行python setup.py build时遇到的错误

hectorASMmodule.c
hectorASMmodule.c(11): warning C4013: '__asm__' sin definir; se supone que extern devuelve como resultado int
hectorASMmodule.c(11): error C2143: error de sintaxis: falta ')' delante de ':'
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe' failed with exit status 2

此答案来自OP作为编辑问题:


我找到了一个解决方案,并正确安装了扩展名。

正如 @peter-cordes所说,我需要更改执行python setup.py build时使用 distrong>的编译器。为此,我做了这些问题以正确解决问题(这就像一个想要在Windows上类似的人的指南(:

1.-检查是否已安装了mingw,如果是的话,将bin文件夹添加到路径。如果正确执行GCC,则可以测试运行GCC。

2.-创建一个名为 distutils.cfg 的文件 python36(。文件内容是:

[build]
compiler=mingw32

3.-编辑文件 cygwincompiler.py 与最后一个文件相同的级别。在那里,您必须添加以支持另一个MSC_VER的代码行:

(prev行代码(:
return ['msvcr100']

(添加此行(:

elif msc_ver == '1700':
   # Visual Studio 2012 / Visual C++ 11.0
   return ['msvcr110']
elif msc_ver == '1800':
   # Visual Studio 2013 / Visual C++ 12.0
   return ['msvcr120']
elif msc_ver == '1900':
   # Visual Studio 2015 / Visual C++ 14.0
   return ['vcruntime140']

(下一行(:

else:   
   raise ValueError("Unknown MS Compiler version %s " % msc_ver)

4.-下载 vcruntime140.dll 并将其复制到您的python-version-folder libs

都是!

现在,您可以运行python setup.py buildpython setup.py install,并将库中的库添加到inline asm((中,将其添加到Python的站点包装文件夹中。

现在,您只需要在一个像 example.py.py 的python项目中执行此操作:

import hectorASM
n = hectorASM.ADD(3, 4)
print(n)

希望这可以帮助其他人。

最新更新