Skip to content

Instantly share code, notes, and snippets.

@bjodah
Last active July 25, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjodah/828aeb4172800d9728b004bd838d6c2b to your computer and use it in GitHub Desktop.
Save bjodah/828aeb4172800d9728b004bd838d6c2b to your computer and use it in GitHub Desktop.
#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); });
}
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])
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