How to write python extensions in pure asm and wou

2019-09-07 03:57发布

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.

3条回答
We Are One
2楼-- · 2019-09-07 04:21

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楼-- · 2019-09-07 04:29

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.

查看更多
我命由我不由天
4楼-- · 2019-09-07 04:41

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

查看更多
登录 后发表回答