ccimport
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
-
ModuleNotFoundError: No module named 'your_module_name'
cause The C++ source file (e.g., `your_module_name.cpp`) either lacks the `// cppimport` comment on the first line, or `ccimport` cannot find the file in the Python import path.fixAdd `// cppimport` as the very first line of `your_module_name.cpp`. Ensure the directory containing `your_module_name.cpp` is in `sys.path` or use `ccimport.load('/path/to/your_module_name.cpp')` with an absolute or relative path. -
Error: C import failed
cause This error typically indicates that the C++ compiler encountered issues when trying to build the extension module, often due to missing header files, incorrect syntax in the C++ code, or an inability to locate necessary libraries (e.g., `pybind11`).fixCheck your C++ code for syntax errors. Ensure all required C++ header files are correctly included and accessible by the compiler. If using `pybind11`, verify it's correctly installed and its headers are discoverable by the build system. Check `ccimport`'s verbose output for specific compiler errors. -
TypeError: 'module' object is not callable
cause This usually happens when you try to call a C++ function directly from the imported Python module object, but the function was not correctly exposed via `pybind11` (or similar binding library) or was misspelled.fixDouble-check the `PYBIND11_MODULE` definition in your C++ code to ensure the function (`m.def("function_name", &function_pointer, "docstring")`) is correctly defined and its name matches what you are calling in Python. Verify the function signature in C++ matches the binding.
Warnings
- gotcha C++ source files intended for `ccimport` (or its underlying mechanism `cppimport`) *must* include the comment `// cppimport` on the first line. Without this, the library will ignore the file, potentially leading to 'module not found' errors or unexpected behavior.
- breaking `ccimport` version 0.3 and above requires Python 3.6+. Older versions (0.2.x) supported Python 3.5. Attempting to use newer `ccimport` versions on Python < 3.6 will result in installation or runtime errors.
- gotcha When distributing applications that use `ccimport`, compiled binaries should be pre-built and included. If `ccimport` is configured for 'release mode' (or similar performance optimizations), it may skip checksum and existence checks. If binaries are missing in this mode, it will cause exceptions instead of recompiling.
Install
-
pip install ccimport
Imports
- ccimport
from ccimport import load # Or similar direct imports for functions like 'load' or 'imp'
import ccimport
Quickstart
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.