Hijack C library functions in D
I like playing with the D programming language and I wrote this little post to show how it’s easy to create a dynamic library (shared object,
.so) that can be invoked in other programs; to have a little fun we will write a D replacement for the
rand() C standard library function call. For your convenience, all the code is also on github
Let’s start with the demo implementation, a C program that calls 10 times the stdlib function
rand() to get a random number.
if we compile and run this program, we get something like this:
Now we will play a little and leverage
LD_PRELOAD to give our program an ‘alternate’ version of
rand() ; this new one will be written in D:
as you can see, after the imports we declare a
rand() function with C linkage; this function doesn’t accept any parameter but needs to return an integer. So we can use advanced phobos functions in the powerful D standard library, together with an easy to read UFCS syntax to read a number from a text file, remove extra whitespaces and convert to an integer. As a result, any program that uses the
rand() function will get the number stored in the text file. Easier than Python, native as C.
As a bonus, I leave here the GNUMakefile used for compilation and test of both programs; I prefer GNU Make format because it doesn’t rely on explicit “TAB” characters so it’s easier to copy and paste.