ccimport

0.4.4 · active · verified Thu Apr 16

ccimport is a lightweight Python package designed for rapidly building C++ bindings for Python. It streamlines the process of compiling and importing C++ extension modules directly from Python code. As of version 0.4.4, it supports Python versions 3.6 and above. The library is actively maintained with periodic releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a C++ function using pybind11, save it to a `.cpp` file, and then use `ccimport.load()` to compile and import it directly into Python. Note the `// cppimport` comment on the first line of the C++ file, which is crucial for `ccimport` to process it.

import ccimport
import os

# Create a dummy C++ file that uses pybind11
cpp_code = '''
// somecode.cpp
// cppimport
#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

// PYBIND11_MODULE must match the base filename (somecode)
PYBIND11_MODULE(somecode, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring
    m.def("add", &add, "A function that adds two numbers");
}
'''

with open('somecode.cpp', 'w') as f:
    f.write(cpp_code)

try:
    # Load the C++ module
    # ccimport.load will automatically compile if needed
    some_module = ccimport.load('somecode.cpp')
    print(f"Result of add(1, 2): {some_module.add(1, 2)}")
except Exception as e:
    print(f"Error loading/executing C++ module: {e}")
finally:
    # Clean up the generated C++ file
    if os.path.exists('somecode.cpp'):
        os.remove('somecode.cpp')
    # ccimport may create a build directory, clean it up if known
    # This part is highly dependent on ccimport's internal logic and temp file naming.
    # For a robust cleanup, one might need to inspect ccimport.settings or known build paths.

view raw JSON →