1-DAV-202 Data Management 2023/24
Previously 2-INF-185 Data Source Integration

Materials · Introduction · Rules · Contact
· Grades from marked homeworks are on the server in file /grades/userid.txt


Difference between revisions of "Lcpp"

From MAD
Jump to navigation Jump to search
Line 2: Line 2:
 
[[HWcpp]]
 
[[HWcpp]]
 
<!-- /NOTEX -->
 
<!-- /NOTEX -->
 +
 +
In this lecture we will write simple C++ extensions for Python.
 +
We will be using [https://pybind11.readthedocs.io/en/stable/basics.html#creating-bindings-for-a-simple-function pybind11] to do that.
 +
 +
Here is an example C++ code, which can be converted as an extension:
 +
 +
<syntaxhighlight lang="C++">
 +
#include <pybind11/pybind11.h>
 +
#include <pybind11/stl.h>
 +
#include <vector>
 +
#include <string>
 +
 +
using std::vector;
 +
using std::string;
 +
 +
 +
// Here is your class code
 +
struct MyClass {
 +
    MyClass() {}
 +
    int f(vector<string> arr) {
 +
        int ss = 0;
 +
        for (auto &s: arr) {
 +
            ss += s.size();
 +
        }
 +
        return ss;
 +
    }
 +
};
 +
 +
 +
// This is the binding code, every function you want to export, must be declared here
 +
PYBIND11_MODULE(example, m) {
 +
    m.doc() = "pybind11 example plugin"; // optional module docstring
 +
 +
    pybind11::class_<MyClass>(m, "MyClass")
 +
        .def(pybind11::init())
 +
        .def("f", &MyClass::f);
 +
}
 +
</syntaxhighlight>

Revision as of 12:55, 12 April 2024

HWcpp

In this lecture we will write simple C++ extensions for Python. We will be using pybind11 to do that.

Here is an example C++ code, which can be converted as an extension:

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
#include <string>

using std::vector;
using std::string;


// Here is your class code
struct MyClass {
    MyClass() {}
    int f(vector<string> arr) {
        int ss = 0;
        for (auto &s: arr) {
            ss += s.size();
        }
        return ss;
    }
};


// This is the binding code, every function you want to export, must be declared here
PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring

    pybind11::class_<MyClass>(m, "MyClass")
        .def(pybind11::init())
        .def("f", &MyClass::f);
}