What is the easiest way to use a DLL
file from within Python
?
Specifically, how can this be done without writing any additional wr
I present a fully worked example on how building a shared library
and using it under Python
by means of ctypes
. I consider the Windows
case and deal with DLLs
. Two steps are needed:
The shared library
I consider is the following and is contained in the testDLL.cpp
file. The only function testDLL
just receives an int
and prints it.
#include
extern "C" {
__declspec(dllexport)
void testDLL(const int i) {
printf("%d\n", i);
}
} // extern "C"
To build a DLL
with Visual Studio
from the command line run
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\vsdevcmd"
to set the include path and then run
cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll
to build the DLL.
DLL
from the IDEAlternatively, the DLL
can be build using Visual Studio
as follows:
Under Python, do the following
import os
import sys
from ctypes import *
lib = cdll.LoadLibrary('testDLL.dll')
lib.testDLL(3)