Algoteka
Log in to submit your own samples!

Create a binding for a C++ function

Problem by oml1111
# Tech tags Title Creator Created date
1 0
cppimport
pybind11
2023-07-11 01:32
View all samples for this language (1 verified and 0 unverified)

Simple solution | Python | cppimport pybind11 |

By oml1111 |
0 likes

Binds a C++ function that adds two integers using the pybind11 and cppimport Python modules.

Note: To make the add function accessible, you need to build the C++ file by running python -m cppimport build from the console

Code

add_ints.cpp

// cppimport
#include <pybind11/pybind11.h>

int add(int a, int b) {
    return a + b;
}

PYBIND11_MODULE(add_ints, m) {
    m.def("add", &add, "Add two integers");
}
/*
<%
setup_pybind11(cfg)
%>
*/

example.py

from add_ints import add
print(add(5, 7))

Further reading

First Steps - pybind11.readthedocs.io
cppimport - Import C++ directly from Python! - github.com

References

macros
PYBIND11_MODULE pybind11.readthedocs.io
pybind11::module_::def pybind11.readthedocs.io

Problem Description

Create a binding for a C++ function and make it callable in your language of choice.

View sample discussion (0 comments)
View problem discussion (0 comments)