Код: Выделить всё
#include
int add(int input_number) {
return input_number + 10;
}
PYBIND11_MODULE(my_module, m) {
m.doc() = "A simple module implemented in C++ to add 10 to a number.";
m.def("add", &add, "Add 10 to a number");
}
< /code>
после < /p>
pip install pybind11
< /code>
Я скомпилирован с: < /p>
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) my_module.cpp -o my_module$(python3-config --extension-suffix)
Код: Выделить всё
import my_module
import pickle
# Use the add function
print(my_module.add(5)) # Outputs: 15
# Attempt to pickle the module
try:
pickle.dumps(my_module)
except TypeError as e:
print(f"Pickling error: {e}") # Expected error
Код: Выделить всё
import my_module
from multiprocessing import Pool
# A wrapper function to call the C++ add function
def parallel_add(number):
return my_module.add(number)
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
try:
# Create a pool of worker processes
with Pool(processes=2) as pool:
results = pool.map(parallel_add, numbers)
print(results) # If successful, prints the results
except Exception as e:
print(f"Multiprocessing error: {e}")
Подробнее здесь: https://stackoverflow.com/questions/793 ... ot-support
Мобильная версия