How to write a simple DLL in C++ for Python

In this article we will see how to write a simple DLL in C++ for Python

  1. Create a file called dlltest.cpp and write a function that sums two numbers and returns the result:
    //dlltest.cpp
    #define DLLEXPORT extern "C" __declspec(dllexport)
    
    DLLEXPORT int sum(int a, int b) {
        return a + b;
    }

    The extern "C" construct tells the compiler that the function is a C function. It also removes the decorations from the functions names in the DLL.
    __declspec(dllexport) adds the export directive to the object file so you do not need to use a .def file.

  2. Include the header of the function in dlltest.h:
    //dlltest.h
    int sum(int, int);
  3. Create a new Dinamic-Link Library project and include the two files, compile, and create the DLL.
  4. You can now use Dependency Walker to see the list of the exported functions. You should see here the sum function.
  5. Move the DLL in the Python folder or use
    >>> import sys
    >>> sys.path.append(r"C:\path\of\dll")
    to include the DLL folder in the list of Python folders.
  6. Use the ctypes module to access the DLL:
    >>> from ctypes import *
    >>> mydll = cdll.dlltest
    >>> mydll
    <CDLL 'dlltest', handle 10000000 at 9e5850>
    Note: ctype module is already included from Python 2.5. If you are using an older version you can download ctypes here.
  7. Now call the function:
    >>> sum = mydll.sum
    >>> sum
    <_FuncPtr object at 0x0097DBE8>
    >>> sum(5, 3)
    8

Ezio Melotti - ©2007 - This work is licensed under a Creative Commons BY-NC-SA 3.0 License.