Skip to content

Instantly share code, notes, and snippets.

@thesamovar
Created January 31, 2020 16:35
Show Gist options
  • Save thesamovar/707fb4c66471bdd7ccb8af8109957a49 to your computer and use it in GitHub Desktop.
Save thesamovar/707fb4c66471bdd7ccb8af8109957a49 to your computer and use it in GitHub Desktop.
/playing_with_pybind11.ipynb
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "%%writefile somecode.cpp\n/*\n<%\nsetup_pybind11(cfg)\n%>\n*/\n#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\nint square(int x) {\n return x * x;\n}\n\n\nPYBIND11_MODULE(somecode, m) {\n m.def(\"square\", &square);\n}",
"execution_count": 1,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Overwriting somecode.cpp\n"
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "import cppimport\nsomecode = cppimport.imp(\"somecode\")\nsomecode.square(9)",
"execution_count": 2,
"outputs": [
{
"data": {
"text/plain": "81"
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "%%writefile testarray.cpp\n/*\n<%\nsetup_pybind11(cfg)\n%>\n*/\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n\nnamespace py = pybind11;\n\ndouble sumit(py::array_t<double, py::array::c_style> arr)\n{\n auto a = arr.unchecked<1>();\n auto ptr = &a(0);\n double s = 0.0;\n for(int i=0; i<a.shape(0); i++)\n {\n s += ptr[i];\n }\n return s;\n}\n\nPYBIND11_MODULE(testarray, m) {\n m.def(\"sumit\", &sumit);\n}",
"execution_count": 3,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "Overwriting testarray.cpp\n"
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "import numpy, cppimport\ntestarray = cppimport.imp(\"testarray\")\nx = numpy.random.rand(10)\nprint(testarray.sumit(x))\nprint(x.sum())",
"execution_count": 4,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "5.5030202270703015\n5.5030202270703015\n"
}
]
}
],
"metadata": {
"kernelspec": {
"name": "conda-env-pybind11-py",
"display_name": "Python [conda env:pybind11]",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.8.1",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"gist": {
"id": "",
"data": {
"description": "/playing_with_pybind11.ipynb",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment