*.so files under Linux are similar to *.dll on windows. They are both shared library, which contain commonly-used functions/classes. The shared library can be loaded into memory whenever needed and if there is a copy in RAM, the OS won’t have to load it again.
There is usually a reference counter for each shared library loaded into RAM and the OS keeps a track of the applications/programs that are still using the shared library and it is up to the OS to decide when to free the shared library from RAM, which is usually when the reference counter falls to zero (no programs are using).
For simple and effective demonstration, I am going to create a small shared library using C++ (not C) and compile it under Ubuntu using GNU C++ Compiler. Finally, I am going to load it in a Python script.
Let us create a folder under /home/pi/TestLib and let us also use your favourite text editor (vi, vim, nano, geditor etc) to create a simple C++ shared library.
// https://helloacm.com
extern "C"
{
// A function adding two integers and returning the result
int SampleAddInt(int i1, int i2)
{
return i1 + i2;
}
// A function doing nothing ;)
void SampleFunction1()
{
// insert code here
}
// A function always returning one
int SampleFunction2()
{
// insert code here
return 1;
}
}
Now, we can compile the C++ shared library using the following command:
g++ -Wall -O3 -shared TestLib.c -o TestLib.so
The -Wall compiler directive prints all warning messages. The -shared tells to compile the source code into a *.so file and -o specifies the output file name. The -O3 turns on all optimisation.
Now we have the shared library TestLib.so which is located at /home/pi/TestLib.
Let us create a simple Python script that invokes the shared library function to add two integers.
#!/usr/bin/python
import ctypes
def main():
TestLib = ctypes.cdll.LoadLibrary('/home/pi/TestLib/TestLib.so')
print TestLib.SampleAddInt(1, 2)
if __name__ == '__main__':
main()
We can then use python TestLib.py or set it executable by chmod +x ./TestLib.py. The example successfully prints 3.
–EOF (The Ultimate Computing & Technology Blog) —
471 wordsLast Post: How to Make a Page Fully Secure over SSL Connections?
Next Post: Learning Responsive CSS Design - 1
