Initialize the NumPy C API by calling the import_array() function:
cpp
void init_numpy()
{
import_array();
}
Define your C++ function that performs the desired operation. Make sure to use the appropriate data types and handle memory management correctly.
cpp
void my_numpy_function(double* input, double* output, int size)
{
for (int i = 0; i < size; i++)
{
// Perform your operation on each element
output[i] = input[i] * 2;
}
}
Create a wrapper function that takes NumPy arrays as input and calls your C++ function:
cpp
void numpy_wrapper(PyObject* input_array, PyObject* output_array)
{
// Extract the data pointers from the NumPy arrays
double* input = reinterpret_cast<double*>(PyArray_DATA(input_array));
double* output = reinterpret_cast<double*>(PyArray_DATA(output_array));
// Get the size of the arrays
int size = PyArray_SIZE(input_array);
// Call your C++ function
my_numpy_function(input, output, size);
}
Build your C++ code, linking against the necessary libraries. For example, using g++:
Import the compiled C++ module into Python and use it like any other NumPy function:
python
import numpy as np
import my_numpy_function
# Create input array
input_array = np.array([1.0, 2.0, 3.0])
# Create output array
output_array = np.empty_like(input_array)
# Call the C++ function
my_numpy_function.numpy_wrapper(input_array, output_array)
print(output_array) # Output: [2.0, 4.0, 6.0]
Note: This is a basic example to get you started. Depending on your specific use case, you may need to handle more complex data types, handle memory allocation differently, or consider other performance optimizations.