beginning chapter on python

This commit is contained in:
Perry Kivolowitz 2023-01-25 22:10:50 -06:00
parent c67f16b7b4
commit 0244471135
5 changed files with 77 additions and 0 deletions

View file

@ -318,6 +318,7 @@ In this section, we present miscellaneous material.
| 3 | [Variadic Functions](./more/varargs/README.md) | [Link](./more/varargs/README.pdf) |
| 4 | [Under the hood: System Calls](./more/system_calls/README.md) | [Link](./more/system_calls/README.pdf) |
| 5 | [Determining string literal lengths for C functions](./more/strlen_for_c/README.md) | [Link](./more/strlen_for_c/README.pdf) |
| 6 | [Calling Assembly Language From Python](./python/) | [Link](./python/README.pdf) |
## Macro Suite

Binary file not shown.

75
python/README.md Normal file
View file

@ -0,0 +1,75 @@
# Python / Assembly Language
It is possible to call your assembly language code from Python. In fact,
it can be insanely easy. It can also be difficult. What differentiates
the two are the arguments you need to pass.
Python stores data ina very different way than C and therefore assembly
language. All Python data types are objects, which for sets and dicts
can make things difficult and outside the scope of this book.
If you want to explore the subject deeply, we suggest
[this link](https://realpython.com/python-bindings-overview)
## Simple EXample
Take this trivial C function:
```c
int square(int x) {
return x * x;
}
```
It could be written in this way using our Apple / Linux convergence
macros:
```text
#include "apple-linux-convergence.S"
/*
gcc -fPIC -shared -o my_square.so function.S
*/
.p2align 2
.text
GLABEL square
#if defined(__APPLE__)
_square:
#else
square:
#endif
mul x0, x0, x0
ret
.end
```
This function is a leaf and requires no interaction with the stack.
Notice there is no `main()`.
Using the following command line, turn your assembly language module
into a "shared object" or .so file:
```text
gcc -fPIC -shared -o my_square.so function.S
```
`-fPIC` means generate position independent code. This allows the library
to be relocated wherever the program loading the library wants it.
Then, in Python:
```python
from ctypes import *
so_file = "./my_square.so"
my_funcs = CDLL(so_file)
print(my_funcs.square(10))
```
It just works.
## More to Come Here

BIN
python/README.pdf Normal file

Binary file not shown.

View file

@ -1,4 +1,5 @@
from ctypes import *
so_file = "./my_square.so"
my_funcs = CDLL(so_file)
print(my_funcs.square(10))