C++ from Python


I was impressed today to see how easy it was to call a C++ DLL from Python. I got the following information from another site:

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

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

Reposted from here… (Thanks!)

I need to get into Python more — I’ve used Ruby a bit but have tended to ignore Python simply because I’ve not seen it is needed. Evidently, I need more side projects.

,

  1. No comments yet.
(will not be published)