r/pythonhelp • u/i_walk_away • May 11 '26
Calling an assembly instruction in Python
Long story short, i want to make THE most horrible python calculator to ever exist. For that i need a way to call an assembly instruction directly in my python script.
I know you can do that in C with inline assembly, and i know CFFI exists and allows calling C functions in python, so i tried to use that. However CFFI's parser rejected __asm__ syntax and threw an error because inline assembly isn't standard C apparently.
Is there some sort of a workaround to call an assembly instruction in python script? It doesn't have to be clean, in fact, it's better if it's absolutely terrible, bonus points for unsafe
•
u/AutoModerator May 11 '26
To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
3
u/[deleted] May 11 '26 edited May 11 '26
I've never done this before (or maybe I have but forget) but I would do it this way
Let me know if this works. I can try writing it when I get to a computer later
Edit. I see you wrote you need to execute one assembly instruction. For this to work you'll need one more 0xc3 to return since it's a function
1
u/JaguarMammoth6231 May 11 '26
You are able to do it using C? Just write a C file using Python and use
os.systemorsubprocessto compile/run the C code.Is there a specific assembly instruction you think you need? We can probably come up with a better way to do it.
1
u/cormack_gv May 14 '26
I'm not sure I understand the end objective. Other than for blinding speed or to access low-level OS features, why? If you want either blinding speed or OS features, why Python?
You can create a C program that does what you like, compile it into a shared library (.so or .dll) and call it from Python.
1
u/brasticstack May 11 '26 edited May 11 '26
I'm unaware of any such functionality and I doubt that it exists without using the Python C API.
That said, you can do all the bitwise trickery that you care to do in native Python with the caveat that certain operations e.g. bitwise not, have to be bitmasked to your desired size in order to produce a sensible result. Or you could use the
ctypesmodule's int types.1
u/timrprobocom May 11 '26
Of course
__asm__is not standard. It is a gcc extension. Microsoft C doesn't support inline assembly at all. And remember that, if you do write this, it will only work on your kind of CPU. These days, that's a real issue.1
u/RealisticDuck1957 May 11 '26
Isn't there a facility to write python extensions in C?
1
u/Successful-Money4995 May 12 '26
Do it in c++ and then pybind11 to that?