-
Notifications
You must be signed in to change notification settings - Fork 2
/
sieve_python_wrapper.cpp
56 lines (47 loc) · 1.51 KB
/
sieve_python_wrapper.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "sieve.h"
static_assert(PY_MAJOR_VERSION == 3, "Python 3 is expected");
#include <vector>
namespace {
PyObject* SieveOfEratosthenesWrapper(PyObject* /*self*/, PyObject* args) {
int n;
if (!PyArg_ParseTuple(args, "I", &n)) {
return nullptr;
}
if (n < 0) {
PyErr_SetString(PyExc_TypeError, "expected non-negative number");
return nullptr;
}
std::vector<size_t> primes = abc::SieveOfEratosthenes(n);
PyObject* result = PyList_New(primes.size());
for(size_t i = 0; i < primes.size(); i++) {
PyList_SetItem(result, i, PyLong_FromLong(primes[i]));
}
return result;
}
PyMethodDef Methods[] = {
PyMethodDef{
"sieve_of_eratosthenes",
SieveOfEratosthenesWrapper,
METH_VARARGS,
"Return list of prime numbers until given number."
},
PyMethodDef{nullptr, nullptr, 0, nullptr} /* Sentinel */
};
PyModuleDef kModuleDefinition{
PyModuleDef_HEAD_INIT,
"cpp_python_extension", /* name of module */
"Python sieve module written in C++", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
Methods,
nullptr,
nullptr,
nullptr,
nullptr
};
} // namespace
extern "C" PyObject* PyInit_cpp_python_extension() {
return PyModule_Create(&kModuleDefinition);
}