-
Notifications
You must be signed in to change notification settings - Fork 14
/
wrappy.cpp
509 lines (409 loc) · 13.4 KB
/
wrappy.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Python header must be included first since they insist on
// unconditionally defining some system macros
// (http://bugs.python.org/issue1045893, still broken in python3.4)
#include <Python.h>
#include <wrappy/wrappy.h>
#include <iostream>
#include <mutex>
#include <cstdio>
namespace wrappy {
PythonObject None, True, False;
} // end namespace wrappy
namespace {
using namespace wrappy;
PyObject *s_EmptyTuple;
PyObject *s_EmptyDict;
__attribute__((constructor))
void wrappyInitialize()
{
// Initialize python interpreter.
// The module search path is initialized as following:
// Python looks at PATH to find an executable called "python"
// The name that is searched can be changed by calling Py_SetProgramName()
// before Py_Initialize(). The folder where this executable resides is
// python-home, which can be overwritten at runtime by setting $PYTHONHOME.
// The default module search path is then
//
// <python-home>/../lib/<python-version>/
//
// All entries from $PYTHONPATH are pre-pended to the module search path
Py_Initialize();
// Setting a dummy value since many libraries require sys.argv[0] to exist
char* dummy_args[] = {const_cast<char*>("wrappy"), nullptr};
PySys_SetArgvEx(1, dummy_args, 0);
wrappy::None = PythonObject(PythonObject::borrowed{}, Py_None);
wrappy::True = PythonObject(PythonObject::borrowed{}, Py_True);
wrappy::False = PythonObject(PythonObject::borrowed{}, Py_False);
s_EmptyTuple = Py_BuildValue("()");
s_EmptyDict = Py_BuildValue("{}");
}
__attribute__((destructor))
void wrappyFinalize()
{
Py_Finalize();
}
PythonObject loadBuiltin(const std::string& name)
{
auto builtins = PyEval_GetBuiltins(); // returns a borrowed reference
PythonObject function(PythonObject::borrowed {},
PyDict_GetItemString(builtins, name.c_str()));
return function;
}
// Load the longest prefix of name that is a valid module name.
// Returns null object if none is.
PythonObject loadModule(const std::string& name, size_t& dot)
{
dot = name.size();
PythonObject module;
while (!module && dot != std::string::npos) {
dot = name.rfind('.', dot-1);
std::string prefix = name.substr(0, dot);
module = PythonObject(PythonObject::owning {},
PyImport_ImportModule(prefix.c_str()));
}
return module;
}
// name must start with a dot
PythonObject loadObject(PythonObject module, const std::string& name)
{
// Evaluate the chain of dot-operators that leads from the module to
// the function.
PythonObject object = module;
size_t suffixDot = 0;
while(suffixDot != std::string::npos) {
size_t next_dot = name.find('.', suffixDot+1);
auto attr = name.substr(suffixDot+1, next_dot - (suffixDot+1));
object = PythonObject(PythonObject::owning {}, PyObject_GetAttrString(object.get(), attr.c_str()));
suffixDot = next_dot;
}
return object;
}
} // end unnamed namespace
namespace wrappy {
PythonObject::PythonObject()
: obj_(nullptr)
{ }
PythonObject::PythonObject(owning, PyObject* value)
: obj_(value)
{ }
PythonObject::PythonObject(borrowed, PyObject* value)
: obj_(value)
{
Py_XINCREF(obj_);
}
PythonObject::~PythonObject()
{
Py_XDECREF(obj_);
}
PythonObject::PythonObject(const PythonObject& other)
: obj_(other.obj_)
{
Py_XINCREF(obj_);
}
PyObject* PythonObject::release()
{
auto res = obj_;
obj_ = nullptr;
return res;
}
PythonObject& PythonObject::operator=(const PythonObject& other)
{
PythonObject tmp(other);
std::swap(obj_, tmp.obj_);
return *this;
}
PythonObject::PythonObject(PythonObject&& other)
: obj_(nullptr)
{
std::swap(obj_, other.obj_);
}
PythonObject& PythonObject::operator=(PythonObject&& other)
{
std::swap(obj_, other.obj_);
return *this;
}
PyObject* PythonObject::get() const
{
return obj_;
}
PythonObject PythonObject::attr(const std::string& name) const
{
return PythonObject(owning{}, PyObject_GetAttrString(obj_, name.c_str()));
}
long long PythonObject::num() const
{
return PyLong_AsLongLong(obj_);
}
double PythonObject::floating() const
{
return PyFloat_AsDouble(obj_);
}
const char* PythonObject::str() const
{
return PyString_AsString(obj_);
}
PythonObject::operator bool() const
{
return obj_ != nullptr;
}
PythonObject PythonObject::operator()() const
{
return PythonObject(owning{}, PyObject_Call(obj_, s_EmptyTuple, s_EmptyDict));
}
PythonObject construct(long long ll)
{
return PythonObject(PythonObject::owning {}, PyLong_FromLongLong(ll));
}
PythonObject construct(int i)
{
return PythonObject(PythonObject::owning {}, PyInt_FromLong(i));
}
PythonObject construct(double d)
{
return PythonObject(PythonObject::owning {}, PyFloat_FromDouble(d));
}
PythonObject construct(const std::string& str)
{
return PythonObject(PythonObject::owning {}, PyString_FromString(str.c_str()));
}
PythonObject construct(const std::vector<PythonObject>& v)
{
PythonObject list(PythonObject::owning {}, PyList_New(v.size()));
for (size_t i = 0; i < v.size(); ++i) {
PyObject* item = v.at(i).get();
Py_XINCREF(item); // PyList_SetItem steals a reference
PyList_SetItem(list.get(), i, item);
}
return list;
}
PythonObject construct(PythonObject object)
{
return object;
}
void addModuleSearchPath(const std::string& path)
{
std::string pathString("path");
auto syspath = PySys_GetObject(&pathString[0]); // Borrowed reference
PythonObject pypath(PythonObject::owning {},
PyString_FromString(path.c_str()));
if (!pypath) {
throw WrappyError("Wrappy: Can't allocate memory for string.");
}
auto pos = PyList_Insert(syspath, 0, pypath.get());
if (pos < 0) {
throw WrappyError("Wrappy: Couldn't add " + path + " to sys.path");
}
}
// Doesn't perform checks on the return value (input is still checked)
PythonObject callFunctionWithArgs(
PythonObject function,
const std::vector<PythonObject>& args,
const std::vector<std::pair<std::string, PythonObject>>& kwargs)
{
if (!PyCallable_Check(function.get())) {
throw WrappyError("Wrappy: Supplied object isn't callable.");
}
// Build tuple
size_t sz = args.size();
PythonObject tuple(PythonObject::owning {}, PyTuple_New(sz));
if (!tuple) {
PyErr_Print();
throw WrappyError("Wrappy: Couldn't create python tuple.");
}
for (size_t i = 0; i < sz; ++i) {
PyObject* arg = args.at(i).get();
Py_XINCREF(arg); // PyTuple_SetItem steals a reference
PyTuple_SetItem(tuple.get(), i, arg);
}
// Build kwargs dict
PythonObject dict(PythonObject::owning {}, PyDict_New());
if (!dict) {
PyErr_Print();
throw WrappyError("Wrappy: Couldn't create python dictionary.");
}
for (const auto& kv : kwargs) {
PyDict_SetItemString(dict.get(), kv.first.c_str(), kv.second.get());
}
PythonObject res(PythonObject::owning{},
PyObject_Call(function.get(), tuple.get(), dict.get()));
if (PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear(); // TODO add string to exception, make custom exception class
throw WrappyError("Wrappy: Exception during call to python function");
}
if (!res) {
throw WrappyError("Wrappy: Error calling function");
}
return res;
}
PythonObject load(
const std::string& name)
{
size_t cutoff;
PythonObject module = loadModule(name, cutoff);
PythonObject object;
if (module) {
object = loadObject(module, name.substr(cutoff));
} else {
// No proper prefix was a valid module, but maybe it's a built-in
object = loadBuiltin(name);
}
if (!object) {
std::string error_message;
if(cutoff != std::string::npos) {
error_message = "Wrappy: Lookup of function " +
name.substr(cutoff) + " in module " +
name.substr(0,cutoff) + " failed.";
} else {
error_message = "Wrappy: Lookup of function " + name + "failed.";
}
throw WrappyError(error_message);
}
return object;
}
PythonObject callWithArgs(
const std::string& name,
const std::vector<PythonObject>& args,
const std::vector<std::pair<std::string, PythonObject>>& kwargs)
{
PythonObject function = load(name);
return callFunctionWithArgs(function, args, kwargs);
}
// Call a python function with arguments args and keyword arguments kwargs
PythonObject callWithArgs(
PythonObject from,
const std::string& functionName,
const std::vector<PythonObject>& args,
const std::vector<std::pair<std::string, PythonObject>>& kwargs)
{
std::string name;
if (functionName[0] == '.') {
name = functionName;
} else {
name = "." + functionName;
}
PythonObject function = loadObject(from, name);
if (!function) {
throw WrappyError("Wrappy: "
"Lookup of function " + functionName + " failed.");
}
return callFunctionWithArgs(function, args, kwargs);
}
//
// PythonIterator implementation
//
PythonIterator::PythonIterator(bool stopped, PythonObject iter):
stopped_(stopped),
iter_(iter)
{}
PythonIterator begin(PythonObject obj)
{
PythonObject pyIter(PythonObject::owning{}, PyObject_GetIter(obj.get()));
PythonIterator iter(false, pyIter);
// Move iterator to first position in list to
// initialize obj_
return ++iter;
}
PythonIterator end(PythonObject)
{
return PythonIterator(true, PythonObject());
}
PythonIterator& PythonIterator::operator++()
{
auto next = iter_.attr("next"); // Change this to __next__ if switching to python 3
// Can't use the normal "call" because we want to actually
// handle the exception
obj_ = PythonObject(PythonObject::owning{},
PyObject_Call(next.get(), s_EmptyTuple, s_EmptyDict));
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_StopIteration) ) {
stopped_ = true;
PyErr_Clear();
} else if (PyErr_Occurred() || !obj_) {
PyErr_Print();
PyErr_Clear();
throw WrappyError("Unexcected exception during iteration");
}
return *this;
}
PythonObject PythonIterator::operator*()
{
return obj_;
}
bool PythonIterator::operator!=(const PythonIterator& other) {
return stopped_ != other.stopped_;
}
//
// wrapFunction implementation
//
namespace {
std::vector<PythonObject> to_vector(PyObject* pyargs)
{
if (!PyTuple_Check(pyargs)) {
throw WrappyError("Trampoling args was no tuple");
}
auto nargs = PyTuple_Size(pyargs);
std::vector<PythonObject> args;
args.reserve(nargs);
for (ssize_t i=0; i<nargs; ++i) {
args.emplace_back(PythonObject::borrowed{}, PyTuple_GetItem(pyargs, i));
}
return args;
}
std::map<const char*, PythonObject> to_map(PyObject* pykwargs)
{
if (!PyDict_Check(pykwargs)) {
throw WrappyError("Trampoling kwargs was no dict");
}
std::map<const char*, PythonObject> kwargs;
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(pykwargs, &pos, &key, &value)) {
const char* str = PyString_AsString(key);
PythonObject obj(PythonObject::borrowed{}, value);
kwargs.emplace(str, obj);
}
return kwargs;
}
PyObject* trampolineWithData(PyObject* data, PyObject* pyargs, PyObject* pykwargs) {
if (!PyCObject_Check(data)) {
throw WrappyError("Trampoline data corrupted");
}
LambdaWithData fun = reinterpret_cast<LambdaWithData>(PyCObject_AsVoidPtr(data));
void* userdata = PyCObject_GetDesc(data);
auto args = to_vector(pyargs);
auto kwargs = to_map(pykwargs);
return fun(args, kwargs, userdata).release();
}
PyObject* trampolineNoData(PyObject* data, PyObject* pyargs, PyObject* pykwargs)
{
if (!PyCObject_Check(data)) {
throw WrappyError("Trampoline data corrupted");
}
Lambda fun = reinterpret_cast<Lambda>(PyCObject_AsVoidPtr(data));
auto args = to_vector(pyargs);
auto kwargs = to_map(pykwargs);
return fun(args, kwargs).release();
}
// The reinterpret_cast<>'s here are technically undefined behaviour, but it's
// the only way that python's C API provides :(
PyMethodDef trampolineNoDataMethod {"trampoline1", reinterpret_cast<PyCFunction>(trampolineNoData), METH_KEYWORDS, nullptr};
PyMethodDef trampolineWithDataMethod {"trampoline2", reinterpret_cast<PyCFunction>(trampolineWithData), METH_KEYWORDS, nullptr};
} // end namespace
PythonObject construct(Lambda lambda)
{
PyObject* pydata = PyCObject_FromVoidPtr(reinterpret_cast<void*>(lambda), nullptr);
return PythonObject(PythonObject::owning{}, PyCFunction_New(&trampolineNoDataMethod, pydata));
}
PythonObject construct(LambdaWithData lambda, void* userdata)
{
PyObject* pydata;
if (!userdata) {
pydata = PyCObject_FromVoidPtr(reinterpret_cast<void*>(lambda), nullptr);
} else { // python returns an error if FromVoidPtrAndDesc is called with desc being null
pydata = PyCObject_FromVoidPtrAndDesc(reinterpret_cast<void*>(lambda), userdata, nullptr);
}
return PythonObject(PythonObject::owning{}, PyCFunction_New(&trampolineWithDataMethod, pydata));
}
typedef PythonObject (*Lambda)(const std::vector<PythonObject>& args, const std::map<const char*, PythonObject>& kwargs);
typedef PythonObject (*LambdaWithData)(const std::vector<PythonObject>& args, const std::map<const char*, PythonObject>& kwargs, void* userdata);
} // end namespace wrappy