Last active
July 25, 2019 14:15
-
-
Save bjodah/828aeb4172800d9728b004bd838d6c2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pybind11/pybind11.h> | |
#include <pybind11/numpy.h> | |
#include <numpy/arrayobject.h> | |
namespace py = pybind11; | |
template<typename T> | |
py::object create_numpy_scalar(T val) { | |
// usage requires initialized NumPy C-API (call _imoprt_array() before use) | |
py::object dt = py::dtype::of<T>(); | |
PyObject * scal = PyArray_Scalar(&val, (PyArray_Descr*)dt.ptr(), py::int_(sizeof(T)).ptr()); | |
return py::reinterpret_steal<py::object>(scal); | |
} | |
PYBIND11_MODULE(_scal, m) { | |
if (_import_array() < 0) { | |
PyErr_SetString(PyExc_ImportError, "numpy.core.multiarray failed to import"); | |
} | |
m.doc() = "pyarray_scalar demo, run like: $ python3 setup.py build_ext -i && python3 test_scal.py"; | |
m.def("get_scalar", []() { return create_numpy_scalar(42.0); }); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from setuptools import setup, Extension | |
import pybind11 | |
ext_mod = Extension( | |
'_scal', ['_scal.cpp'], | |
language='c++', extra_compile_args=['-std=c++14', '-fmax-errors=3'], | |
include_dirs=[pybind11.get_include(), pybind11.get_include(user=True)]) | |
setup(name='_scal', ext_modules=[ext_mod]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from _scal import get_scalar | |
print(get_scalar()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment