I would like to thank Richard MacCutchan for his helpful solution. Using that i figured out a way to call dlls from python code.
1. Firstly if your python application is 64 bit, the dll which you create using MingW should also be 64 bit. so make sure to download a compatible version of the dll file.
2. Please do not create shared objects and try to import them, it wont work.
Shared objects are used in POSIX systems. If you do so you will get the below error:
Quote:
Traceback (most recent call last):
File "function.py", line 3, in <module>
hllDll = ctypes.WinDLL ("someso.dll")
File "C:\Python35\lib\ctypes\__init__.py", line 347, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application
Lets say we have a below c program in a file called mydll.c:
__declspec(dllexport) int __cdecl Add(int a, int b)
{
return (a + b);
}
- ____declspec(dllexport): This basically allows us to specify a storage class specifier.
- This indicates to the compiler that a function or an objecy is being exported from a dll file.
- Similarly there is another storage class specifier called dllimport, this tells the compiler that the
exported object can be imported in an other file.
Note: You can use a Mingw compiler as per your python application i.e 32 or 64 bit.
You can compile using below steps:
gcc -c mydll.c
gcc -o basicDLL.dll -s -shared mydll.o -Wl,--subsystem,windows
python basicApplication.py
python basicApplication.py
Lets look at the flags used in the above commands for compilation:
-Wl: All which follow this flag are passed as an argument to the linker.
This eventually will become a linker call as below:
ld --subsystem windows
Basically this call will instruct the linker to set PE header subsystem type to windows.
This will indicate that a dll is to be created which is compiled using mingw and is to be run in windows.
Lets look at the python side code:
from ctypes import *
lib = CDLL('basicDLL')
print (lib.Add(1,2))
Name that file to anything lets say basicApplication.py and lets run it.
The output is 3
Please note: Making any changes in the dll, will have to be rebuilt again. Which means you first compile the .c file and then generate a dll out of it.
ctypes is a module which is very helpful to extend c and python functionalities with each other.