diff --git a/README.md b/README.md index d4df124..00e72b3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/README.pdf b/README.pdf index 7fbaeae..5d73fee 100644 Binary files a/README.pdf and b/README.pdf differ diff --git a/python/README.md b/python/README.md new file mode 100644 index 0000000..8736f59 --- /dev/null +++ b/python/README.md @@ -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 diff --git a/python/README.pdf b/python/README.pdf new file mode 100644 index 0000000..d7e7297 Binary files /dev/null and b/python/README.pdf differ diff --git a/python/test.py b/python/test.py index 9209714..2067b58 100644 --- a/python/test.py +++ b/python/test.py @@ -1,4 +1,5 @@ from ctypes import * + so_file = "./my_square.so" my_funcs = CDLL(so_file) print(my_funcs.square(10))