Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
Chapter 14 — Importing C++ Programs in Python: Exercise Solutions Guide
How to Use This Page
1. Attempt every exercise in your Samacheer Kalvi textbook on your own first. 2. Compare your answers with the solutions below — focus on the method, not just the final result. 3. Practise the Python programs on a computer; compile the C++ examples and test the integration. 4. Review the Common Mistakes and Exam Checklist before your exam.
Key Concepts
Why Interface Python with C++?
- Performance: C++ runs faster than Python for CPU-intensive tasks (numerical computation, image processing).
- Legacy code: Reuse existing C++ libraries without rewriting in Python.
- System-level access: C++ provides low-level control that Python cannot.
Methods of Integration
| Method | Description | Complexity |
|---|---|---|
os.system() | Run a command-line program from Python | Low |
subprocess module | More control over external processes | Low |
sys.argv | Accept command-line arguments in Python | Low |
ctypes | Call functions from shared libraries (.so/.dll) | Medium |
| SWIG | Auto-generate Python wrappers for C++ | High |
ctypes Data Types Mapping
| Python (ctypes) | C Type | Description |
|---|---|---|
c_int | int | Integer |
c_float | float | Floating point |
c_double | double | Double precision |
c_char_p | char* | String (null-terminated) |
c_void_p | void* | Generic pointer |
Multiple Choice Questions
Q1. Which module provides access to command-line arguments in Python?
- (a)
os  (b)sys  (c)ctypes  (d)subprocess
Q2. What does sys.argv[0] contain?
- (a) First argument   (b) Script name   (c) Number of arguments   (d) Environment path
Q3. Which Python module allows calling C functions from shared libraries?
- (a)
os  (b)subprocess  (c)ctypes  (d)signal
Q4. What does os.system() return?
- (a) Output of the command   (b) Exit status (return code)   (c) Process ID   (d) File handle
Q5. SWIG stands for:
- (a) Simple Web Interface Generator   (b) Simplified Wrapper and Interface Generator   (c) System Wide Integration Gateway   (d) Standard Widget Library
Q6. On Linux, a shared library file has the extension:
- (a)
.dll  (b).lib  (c).so  (d).pyd
Fill in the Blanks
1. The module used to run system commands from Python is ______. → os (or subprocess) 2. sys.argv is a ______ data structure containing command-line arguments. → list 3. The ctypes data type corresponding to C's int is ______. → c_int 4. A file with .so extension on Linux is called a ______ library. → shared (or dynamic) 5. SWIG generates ______ code that allows Python to call C++ functions. → wrapper (or binding) 6. os.system() returns the ______ code of the executed command. → exit (or return)
True or False
sys.argv arguments are always strings, even if numbers are passed.Match the Following
| Column A | Column B |
|---|---|
1. sys.argv | a. Simplified Wrapper and Interface Generator |
2. os.system() | b. Command-line arguments as a list |
3. ctypes | c. Run system command, return exit code |
| 4. SWIG | d. Call functions from shared libraries |
5. subprocess | e. More control over external processes |
Short Answer Questions
Q1. What is sys.argv? Explain with an example.
sys.argv is a list in the sys module that holds command-line arguments passed to a Python script. sys.argv[0] is the script name; subsequent elements are the arguments.
# script.py
import sys
print("Script:", sys.argv[0])
print("Arguments:", sys.argv[1:])
print("Number of arguments:", len(sys.argv) - 1)
Run: python script.py hello 42
Output:
Q2. What is os.system()? Give an example.
os.system() executes a command in the system shell and returns the exit code (0 for success).
import os
# Compile a C++ program
result = os.system("g++ -o add add.cpp")
if result == 0:
print("Compilation successful")
else:
print("Compilation failed")
Limitation: It cannot capture the command's output. Use subprocess for that.
Q3. What is the subprocess module? How is it better than os.system()?
The subprocess module provides more control over process creation:
import subprocess
# Capture output
result = subprocess.run(
["echo", "Hello"],
capture_output=True,
text=True
)
print(result.stdout) # Captured output
print(result.returncode) # Exit code
Advantages over os.system(): can capture stdout/stderr, pass input, set timeouts, and use list arguments (safer against shell injection).
Q4. What is ctypes? List four ctypes data types.
ctypes is a built-in Python module for calling functions in shared libraries (.so on Linux, .dll on Windows).
| ctypes Type | C Equivalent |
|---|---|
c_int | int |
c_float | float |
c_double | double |
c_char_p | char* (string) |
Q5. What is SWIG? What are its advantages?
SWIG (Simplified Wrapper and Interface Generator) automatically creates Python bindings from C/C++ header files.
Advantages:
- No need to write wrapper functions manually
- Supports classes, overloaded functions, templates
- Works with many scripting languages (Python, Perl, Ruby, etc.)
- Generates documentation-ready interfaces
Detailed Answer Questions
Q1. Explain the steps to call a C++ function from Python using ctypes.
Step 1: Write the C++ function with extern "C" linkage:
// add.cpp
extern "C" {
int add(int a, int b) {
return a + b;
}
float multiply(float a, float b) {
return a * b;
}
}
Step 2: Compile into a shared library:
# Linux
g++ -shared -fPIC -o libadd.so add.cpp
# Windows
g++ -shared -o add.dll add.cpp
Step 3: Load and call from Python:
import ctypes
# Load the shared library
lib = ctypes.CDLL("./libadd.so") # Linux
# lib = ctypes.CDLL("./add.dll") # Windows
# Specify argument and return types
lib.add.argtypes = [ctypes.c_int, ctypes.c_int]
lib.add.restype = ctypes.c_int
# Call the function
result = lib.add(10, 20)
print(f"10 + 20 = {result}") # Output: 10 + 20 = 30
# For float function
lib.multiply.argtypes = [ctypes.c_float, ctypes.c_float]
lib.multiply.restype = ctypes.c_float
result = lib.multiply(3.5, 2.0)
print(f"3.5 * 2.0 = {result}") # Output: 3.5 * 2.0 = 7.0
Why extern "C"? C++ uses name mangling (encoding function names with type info). extern "C" tells the compiler to use C-style linking, making the function findable by name in the shared library.
Q2. Write a Python program that uses subprocess to compile and run a C++ program.
import subprocess
import sys
# Step 1: Write a simple C++ source file
cpp_code = """
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Sum = " << a + b << endl;
return 0;
}
"""
# Save the source code
with open("sum.cpp", "w") as f:
f.write(cpp_code)
# Step 2: Compile the C++ program
compile_result = subprocess.run(
["g++", "-o", "sum", "sum.cpp"],
capture_output=True,
text=True
)
if compile_result.returncode != 0:
print("Compilation failed:")
print(compile_result.stderr)
sys.exit(1)
print("Compilation successful.")
# Step 3: Run the compiled program
# Provide input via stdin
run_result = subprocess.run(
["./sum"],
input="10 20\n",
capture_output=True,
text=True
)
print("Program output:")
print(run_result.stdout)
Q3. Explain SWIG with an example of wrapping a C++ function for Python.
Step 1: Write the C++ header:
// math_operations.h
int factorial(int n);
double square_root(double x);
Step 2: Write the C++ implementation:
// math_operations.cpp
#include "math_operations.h"
#include <cmath>
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
double square_root(double x) {
return std::sqrt(x);
}
Step 3: Create the SWIG interface file:
// math_operations.i
%module math_operations
%{
#include "math_operations.h"
%}
%include "math_operations.h"
Step 4: Generate wrapper and compile:
# Generate wrapper code
swig -python -c++ math_operations.i
# Compile into shared library
g++ -shared -fPIC -I/usr/include/python3.x \
math_operations_wrap.cxx math_operations.cpp \
-o _math_operations.so
Step 5: Use in Python:
import math_operations
print(math_operations.factorial(5)) # Output: 120
print(math_operations.square_root(16.0)) # Output: 4.0
Q4. Compare the different methods of integrating Python with C++.
| Feature | os.system() | subprocess | ctypes | SWIG |
|---|---|---|---|---|
| Complexity | Very Low | Low | Medium | High |
| Captures output | No | Yes | N/A (direct call) | N/A (direct call) |
| Direct function call | No | No | Yes | Yes |
| Data type handling | N/A | Strings only | Manual mapping | Automatic |
| C++ classes | No | No | No (C only) | Yes |
| Performance | Low (process spawn) | Low (process spawn) | High (in-process) | High (in-process) |
| Installation needed | No | No | No | Yes (SWIG tool) |
When to use which:
os.system()/subprocess: Quick one-off commands, compile-and-run workflowsctypes: Calling specific functions from existing shared libraries- SWIG: Large C++ codebases with classes and complex types
Q5. Write a Python program that accepts command-line arguments and performs arithmetic operations.
# calc.py
import sys
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero"
return a / b
if len(sys.argv) != 4:
print("Usage: python calc.py <operation> <num1> <num2>")
print("Operations: add, sub, mul, div")
sys.exit(1)
operation = sys.argv[1]
try:
num1 = float(sys.argv[2])
num2 = float(sys.argv[3])
except ValueError:
print("Error: Arguments must be numbers.")
sys.exit(1)
operations = {
"add": add,
"sub": subtract,
"mul": multiply,
"div": divide
}
if operation not in operations:
print(f"Error: Unknown operation '{operation}'")
print("Available: add, sub, mul, div")
sys.exit(1)
result = operations[operation](num1, num2)
print(f"{num1} {operation} {num2} = {result}")
Usage:
Common Mistakes
| Mistake | Why It's Wrong | Fix |
|---|---|---|
Accessing sys.argv[1] without checking len(sys.argv) | Causes IndexError if no arguments are passed | Always check len(sys.argv) before accessing |
Not converting sys.argv values from strings | sys.argv always returns strings; "10" + "20" = "1020" not 30 | Use int() or float() to convert |
Using os.system() to capture output | os.system() only returns the exit code | Use subprocess.run() with capture_output=True |
Forgetting extern "C" in C++ code for ctypes | C++ name mangling prevents finding the function | Wrap functions with extern "C" { ... } |
Not setting argtypes and restype in ctypes | Python assumes c_int return type; wrong for floats/strings | Always set both argtypes and restype |
Compiling without -fPIC -shared flags | Shared library won't be created properly | Use g++ -shared -fPIC -o libname.so file.cpp |
Exam Checklist
- [ ] Can explain why Python needs to interface with C++ (performance, legacy code)
- [ ] Can use
sys.argvto accept and process command-line arguments - [ ] Can use
os.system()andsubprocess.run()to execute external commands - [ ] Can explain ctypes data types and their C equivalents
- [ ] Can write, compile, and call a C++ function from Python using ctypes
- [ ] Can explain the SWIG workflow (interface file, generation, compilation)
- [ ] Know the advantages and limitations of each integration method
- [ ] Can convert
sys.argvstring arguments to numeric types - [ ] Understand why
extern "C"is needed when using ctypes with C++ - [ ] Can compare
os.system(),subprocess,ctypes, and SWIG
