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
· Dates of project submission and oral exams:
Early: submit project May 24 9:00am, oral exams May 27 1:00pm (limit 5 students).
Otherwise submit project June 11, 9:00am, oral exams June 18 and 21 (estimated 9:00am-1:00pm, schedule will be published before exam).
Sign up for one the exam days in AIS before June 11.
Remedial exams will take place in the last week of the exam period. Beware, there will not be much time to prepare a better project. Projects should be submitted as homeworks to /submit/project.
· Cloud homework is due on May 20 9:00am.


Lcpp

From MAD
Revision as of 11:57, 12 April 2024 by Teacher (talk | contribs)
Jump to navigation Jump to search

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);
}

We can then compile this code to be used as Python module: c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cc -o example$(python3-config --extension-suffix)

And then we can import it (we need to be in same directory as compiled output):

import example

c = example.MyClass()
print(c.f(["aaa", "bb"]))
print(c.f([]))