Easy way to Call C++ function from python

This post teaches you how to call a C++ (cpp) code or function from python.

Step 1: Develop a C wrapper for CPP as mentioned below

Assume you have a C++ DLL project with CPP files and HPP files

  1. Create CLibrary.H and CLibrary.C files and add to C++ DLL project
  2. CLibrary.H should contain following code.
#define DLLEXPORT __declspec(dllexport)
    #ifdef __cplusplus
        #define EXTERNFUNC extern "C"
        #define EXTERNFUNC extern

EXTERNFUNC DLLEXPORT void __cdecl CSourceParseDefinitionFile(
        _LibraryInstance *_instance, const char* fileName);

3. CLibrary.C should contain following code.

#include " CLibrary.h"
//Add required .hpp files

EXTERNFUNC DLLEXPORT void __cdecl  BookCSourceParseBook(
    _Gm3Instance *_instance, const char* fileName)
// Add code to create required Class objects and get required reference to _instance


4. Create DLL from DLL project.

5. Use the DLL in a C Executable project by adding file CLibrary.h to the C Executable project

Step 2: Call C APIs from python using ctypes

Below is the example to call C APIs from Python

from ctypes import * 
# Load the dll or shared library into c types. 
libc = ctypes.CDLL("msvcrt.dll") 
# Call the C function from the library 

About the Author


A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published. Required fields are marked *