如何让 Python 使用 Assembly [英] How to get Python to use Assembly

查看:20
本文介绍了如何让 Python 使用 Assembly的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是汇编初学者,但 Python 高手.我最近才开始学习 x86_64 NASM for windows,我希望结合汇编的力量和 Python 的灵活性.我已经查看了所有内容,但没有找到在 Python 中使用 NASM 汇编程序的方法.我的意思不是在线组装.我希望编写一个汇编程序,编译它,然后以某种方式提取该过程以在我的 Python 程序中使用.有人可以举例说明如何做到这一点,因为我完全迷失了.

I am a beginner in assembly, but a master in Python. I have just recently started to learn x86_64 NASM for windows, and I wish to combine the power of assembly, and the flexibility of Python. I have looked all over, and I have not found a way to use a NASM assembly procedure from within Python. By this I do not mean in-line assembly. I wish to write an assembly program, compile it, and then somehow extract the procedure to use in my Python program. Can someone illustrate a simple example of how to do this, as I am completely lost.

推荐答案

你可以创建一个 C 扩展 汇编中实现的函数的包装器,并将其链接到由 nasm 创建的 OBJ 文件.

You could create a C extension wrapper for the functions implemented in assembly and link it to the OBJ file created by nasm.

一个虚拟示例(用于 32 位 Python 2;未测试):

A dummy example (for 32 bit Python 2; not tested):

myfunc.asm:

;http://www.nasm.us/doc/nasmdoc9.html
global  _myfunc 
section .text
_myfunc: 
    push    ebp 
    mov     ebp,esp 
    sub     esp,0x40        ; 64 bytes of local stack space 
    mov     ebx,[ebp+8]     ; first parameter to function 
    ; some more code 
    leave
    ret

myext.c:

#include <Python.h>

void myfunc(void);

static PyObject*
py_myfunc(PyObject* self, PyObject* args)
{
    if (!PyArg_ParseTuple(args, ""))
        return NULL;
    myfunc();
    Py_RETURN_NONE;
}

static PyMethodDef MyMethods[] =
{
    {"myfunc", py_myfunc, METH_VARARGS, NULL},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initmyext(void)
{
    (void) Py_InitModule("myext", MyMethods);
}

setup.py:

from distutils.core import setup, Extension
setup(name='myext', ext_modules=[
    Extension('myext', ['myext.c'], extra_objects=['myfunc.obj'])])

构建并运行:

nasm -fwin32 myfunc.asm

python setup.py build_ext --inplace

python -c"import myext;myext.myfunc()"

这篇关于如何让 Python 使用 Assembly的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆