How to write python extensions in pure asm and would it be efficient?

◇◆丶佛笑我妖孽 提交于 2019-12-12 03:43:45

问题


I have medium amateur skills in Python and I'm beginner in asm and haven't any knowledge of C-language.

I know that python C-extensions must follow specific interface to work fine.

Is this possible to write python extension in pure Assembly with the right interface and full functionality? The second question is would it be efficient enough if case of doing it right?

While googling I haven't found any examples of code or some articles or solutions about this question.

And this ISN'T the question about running asm-code from within Python so it's not duplicate of topics on SO.


回答1:


How to do it:

I don't know if you could do it 'purely' in assembly, but: If you make a "proxy class" (lets call it that way) in C that calls the assembly function, and you then write the assembler with the C convention, then, by simply compiling the assembler code:

nasm -felf64 -g -F dwarf assembly_function.asm

and then, using a setup.py file containing:

from distutils.core import setup, Extension
setup(name='assembly_include_name', version='1.0', ext_modules=[Extension('assembly_include_name', ['c_assembly_proxy.c'],extra_objects=["assembly_function.o"])])

you will be able to do what you wanted. Notice that you have to add the parameter "extra_objects" to the Extension constructor in order to tell python to link the assembly code, otherwise it will crash saying that it can't find the function's name.

Why would you do it:

If you want to use SSE instructions (SSE2, SSE3...) regardless the optimization the compiler could make.

Extension api: https://docs.python.org/2/extending/extending.html

disutils.core reference: https://docs.python.org/2/distutils/apiref.html?highlight=distutils.core#module-distutils.core




回答2:


In theory - it is possible.

In practice - it is highly impractical to do so.

There are very very few cases where there is justified usage of Assembly over C, and even if you face such a situation, it is highly unlikely you will be working with Python in that case.

Also note, that the compiler can optimize the C code to extremely efficient assembly. In fact it is highly unlikely that you will hand write assembly and it will be more efficient that the compiler output, unless you are have extremely potent assembly skills, or have been writing assembly all your life..




回答3:


You could write your asm as inline asm inside your c extention, as for efficiency...

Teapot.

Efficiency isn't measured by the choice of language, its measured by how well its implemented and how well its designed.



来源:https://stackoverflow.com/questions/14546610/how-to-write-python-extensions-in-pure-asm-and-would-it-be-efficient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!