Current Affairs updated daily
KalviGavaniKalviGavani
Class 12 · Tamil Nadu State Board

Samacheer Kalvi 12th Computer Science Chapter 14 Importing C++ Programs in Python Exercise Solutions | KalviGavani

Complete TN Board Class 12 Computer Science Chapter 14 Importing C++ Programs in Python exercise solutions — ctypes, SWIG, command-line interfacing, sys.argv, os.system, shared libraries, and worked code examples.

Updated 13 June 202611 min read

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

MethodDescriptionComplexity
os.system()Run a command-line program from PythonLow
subprocess moduleMore control over external processesLow
sys.argvAccept command-line arguments in PythonLow
ctypesCall functions from shared libraries (.so/.dll)Medium
SWIGAuto-generate Python wrappers for C++High

ctypes Data Types Mapping

Python (ctypes)C TypeDescription
c_intintInteger
c_floatfloatFloating point
c_doubledoubleDouble precision
c_char_pchar*String (null-terminated)
c_void_pvoid*Generic pointer

Multiple Choice Questions

Q1. Which module provides access to command-line arguments in Python?

  • (a) os   (b) sys   (c) ctypes   (d) subprocess
Answer(b) sys — sys.argv is a list containing the script name and all command-line arguments.

Q2. What does sys.argv[0] contain?

  • (a) First argument   (b) Script name   (c) Number of arguments   (d) Environment path
Answer(b) Script name — sys.argv[0] always holds the script's filename; actual arguments start at index 1.

Q3. Which Python module allows calling C functions from shared libraries?

  • (a) os   (b) subprocess   (c) ctypes   (d) signal
Answer(c) ctypes — it provides cdll, windll, and oledll for loading shared libraries.

Q4. What does os.system() return?

  • (a) Output of the command   (b) Exit status (return code)   (c) Process ID   (d) File handle
Answer(b) Exit status (return code) — 0 means success; non-zero means an error occurred.

Q5. SWIG stands for:

  • (a) Simple Web Interface Generator   (b) Simplified Wrapper and Interface Generator   (c) System Wide Integration Gateway   (d) Standard Widget Library
Answer(b) Simplified Wrapper and Interface Generator — SWIG generates wrapper code to call C/C++ from scripting languages.

Q6. On Linux, a shared library file has the extension:

  • (a) .dll   (b) .lib   (c) .so   (d) .pyd
Answer(c) .so — shared object files on Linux. Windows uses .dll.

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

1. sys.argv arguments are always strings, even if numbers are passed.
AnswerTrue — convert with int() or float() as needed. 2. os.system() can capture the output of a command as a string. → False — it only returns the exit code; use subprocess.run() to capture output. 3. ctypes can only call C functions, not C++ functions directly. → True — C++ name mangling prevents direct calls; use extern "C" wrapper functions. 4. SWIG requires writing interface files (.i) to generate bindings. → True — SWIG uses .i interface files to know which functions and classes to wrap. 5. Python code calling C++ via ctypes is always faster than pure Python. → True — for computation-heavy tasks, the C++ overhead is negligible compared to Python's interpretation cost. 6. subprocess.call() is an older, less flexible alternative to subprocess.run(). → True — subprocess.run() (Python 3.5+) is the recommended replacement.

Match the Following

Column AColumn B
1. sys.argva. Simplified Wrapper and Interface Generator
2. os.system()b. Command-line arguments as a list
3. ctypesc. Run system command, return exit code
4. SWIGd. Call functions from shared libraries
5. subprocesse. More control over external processes
Answer1-b, 2-c, 3-d, 4-a, 5-e

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:

Script: script.py Arguments: ['hello', '42'] Number of arguments: 2

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 TypeC Equivalent
c_intint
c_floatfloat
c_doubledouble
c_char_pchar* (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++.

Featureos.system()subprocessctypesSWIG
ComplexityVery LowLowMediumHigh
Captures outputNoYesN/A (direct call)N/A (direct call)
Direct function callNoNoYesYes
Data type handlingN/AStrings onlyManual mappingAutomatic
C++ classesNoNoNo (C only)Yes
PerformanceLow (process spawn)Low (process spawn)High (in-process)High (in-process)
Installation neededNoNoNoYes (SWIG tool)

When to use which:

  • os.system() / subprocess: Quick one-off commands, compile-and-run workflows
  • ctypes: 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:

python calc.py add 10 20 10.0 add 20.0 = 30.0 python calc.py mul 5 3 5.0 mul 3.0 = 15.0

Common Mistakes

MistakeWhy It's WrongFix
Accessing sys.argv[1] without checking len(sys.argv)Causes IndexError if no arguments are passedAlways check len(sys.argv) before accessing
Not converting sys.argv values from stringssys.argv always returns strings; "10" + "20" = "1020" not 30Use int() or float() to convert
Using os.system() to capture outputos.system() only returns the exit codeUse subprocess.run() with capture_output=True
Forgetting extern "C" in C++ code for ctypesC++ name mangling prevents finding the functionWrap functions with extern "C" { ... }
Not setting argtypes and restype in ctypesPython assumes c_int return type; wrong for floats/stringsAlways set both argtypes and restype
Compiling without -fPIC -shared flagsShared library won't be created properlyUse 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.argv to accept and process command-line arguments
  • [ ] Can use os.system() and subprocess.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.argv string arguments to numeric types
  • [ ] Understand why extern "C" is needed when using ctypes with C++
  • [ ] Can compare os.system(), subprocess, ctypes, and SWIG

Frequently Asked Questions

Through sys.argv, a list where sys.argv[0] is the script name and sys.argv[1], sys.argv[2], etc. are the arguments passed from the command line.
← Browse all Class 12 Exercise Solutions

More exercise solutions