如何让Python使用Assembly

我是一名汇编初学者,但是是Python的高手。 我刚刚开始学习x86_64 NASM for windows,我希望结合汇编的强大function和Python的灵活性。 我已经看遍了,我还没有find一种在Python中使用NASM汇编程序的方法。 通过这个我不是说在线汇编。 我希望编写一个汇编程序,编译它,然后以某种方式提取在我的Python程序中使用的过程。 有人可以举例说明如何做到这一点,因为我完全失去了。

您可以为汇编中实现的函数创建C扩展包装,并将其链接到由nasm创建的OBJ文件。

一个虚拟的例子(对于32位的Python 2;未经测试):

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_Initmodulee("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程序中嵌入程序集:

这些工作通过编译程序集并在运行时将其加载到可执行的内存中。 前三个项目使用Python实现x86汇编程序,而最后一个项目调用外部编译器。

不确定组装的“权力”,真的。

你可以从这里开始: https : //docs.python.org/2/extending/extending.html

这是关于使用C或C ++编写的代码扩展python,但原则应该是相同的(C实际上只是一个可移植的宏汇编器)。