Blender V5.3
py_capi_utils.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
11
12/* Future-proof, See https://docs.python.org/3/c-api/arg.html#strings-and-buffers */
13#define PY_SSIZE_T_CLEAN
14
15#include <Python.h>
16#include <frameobject.h>
17
18#include "BLI_utildefines.hh" /* for bool */
19
20#include "DNA_vec_types.h" /* for rcti */
21
22#include "py_capi_utils.hh"
23
24#include "python_utildefines.hh"
25
26#ifndef MATH_STANDALONE
27# include "MEM_guardedalloc.h"
28
29# include "BLI_string_utf8.hh"
30#endif
31
32#ifdef _WIN32
33# include "BLI_math_base_c.hh" /* isfinite() */
34#endif
35
36namespace blender {
37
38/* -------------------------------------------------------------------- */
41
43 const size_t array_item_size,
44 PyObject *value_fast,
45 const Py_ssize_t length,
46 const PyTypeObject *type,
47 const char *error_prefix)
48{
49 const Py_ssize_t value_len = PySequence_Fast_GET_SIZE(value_fast);
50 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
51 Py_ssize_t i;
52
53 BLI_assert(PyList_Check(value_fast) || PyTuple_Check(value_fast));
54
55 if (value_len != length) {
56 PyErr_Format(PyExc_TypeError,
57 "%.200s: invalid sequence length. expected %d, got %d",
58 error_prefix,
59 length,
60 value_len);
61 return -1;
62 }
63
64 /* for each type */
65 if (type == &PyFloat_Type) {
66 switch (array_item_size) {
67 case sizeof(double): {
68 double *array_double = static_cast<double *>(array);
69 for (i = 0; i < length; i++) {
70 array_double[i] = PyFloat_AsDouble(value_fast_items[i]);
71 }
72 break;
73 }
74 case sizeof(float): {
75 float *array_float = static_cast<float *>(array);
76 for (i = 0; i < length; i++) {
77 array_float[i] = PyFloat_AsDouble(value_fast_items[i]);
78 }
79 break;
80 }
81 default: {
82 /* Internal error. */
84 }
85 }
86 }
87 else if (type == &PyLong_Type) {
88 switch (array_item_size) {
89 case sizeof(int64_t): {
90 int64_t *array_int = static_cast<int64_t *>(array);
91 for (i = 0; i < length; i++) {
92 array_int[i] = PyC_Long_AsI64(value_fast_items[i]);
93 }
94 break;
95 }
96 case sizeof(int32_t): {
97 int32_t *array_int = static_cast<int32_t *>(array);
98 for (i = 0; i < length; i++) {
99 array_int[i] = PyC_Long_AsI32(value_fast_items[i]);
100 }
101 break;
102 }
103 case sizeof(int16_t): {
104 int16_t *array_int = static_cast<int16_t *>(array);
105 for (i = 0; i < length; i++) {
106 array_int[i] = PyC_Long_AsI16(value_fast_items[i]);
107 }
108 break;
109 }
110 case sizeof(int8_t): {
111 int8_t *array_int = static_cast<int8_t *>(array);
112 for (i = 0; i < length; i++) {
113 array_int[i] = PyC_Long_AsI8(value_fast_items[i]);
114 }
115 break;
116 }
117 default: {
118 /* Internal error. */
120 }
121 }
122 }
123 else if (type == &PyBool_Type) {
124 switch (array_item_size) {
125 case sizeof(int64_t): {
126 int64_t *array_bool = static_cast<int64_t *>(array);
127 for (i = 0; i < length; i++) {
128 array_bool[i] = (PyLong_AsLong(value_fast_items[i]) != 0);
129 }
130 break;
131 }
132 case sizeof(int32_t): {
133 int32_t *array_bool = static_cast<int32_t *>(array);
134 for (i = 0; i < length; i++) {
135 array_bool[i] = (PyLong_AsLong(value_fast_items[i]) != 0);
136 }
137 break;
138 }
139 case sizeof(int16_t): {
140 int16_t *array_bool = static_cast<int16_t *>(array);
141 for (i = 0; i < length; i++) {
142 array_bool[i] = (PyLong_AsLong(value_fast_items[i]) != 0);
143 }
144 break;
145 }
146 case sizeof(int8_t): {
147 int8_t *array_bool = static_cast<int8_t *>(array);
148 for (i = 0; i < length; i++) {
149 array_bool[i] = (PyLong_AsLong(value_fast_items[i]) != 0);
150 }
151 break;
152 }
153 default: {
154 /* Internal error. */
156 }
157 }
158 }
159 else {
160 PyErr_Format(PyExc_TypeError, "%s: internal error %s is invalid", error_prefix, type->tp_name);
161 return -1;
162 }
163
164 if (PyErr_Occurred()) {
165 PyErr_Format(PyExc_TypeError,
166 "%s: one or more items could not be used as a %s",
167 error_prefix,
168 type->tp_name);
169 return -1;
170 }
171
172 return 0;
173}
174
176 const size_t array_item_size,
177 PyObject *value,
178 const Py_ssize_t length,
179 const PyTypeObject *type,
180 const char *error_prefix)
181{
182 PyObject *value_fast;
183 int ret;
184
185 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
186 return -1;
187 }
188
189 ret = PyC_AsArray_FAST(array, array_item_size, value_fast, length, type, error_prefix);
190 Py_DECREF(value_fast);
191 return ret;
192}
193
194static int PyC_AsArray_Multi_impl(void **array_p,
195 const size_t array_item_size,
196 PyObject *value,
197 const int *dims,
198 const int dims_len,
199 const PyTypeObject *type,
200 const char *error_prefix);
201
202static int PyC_AsArray_Multi_FAST_impl(void **array_p,
203 const size_t array_item_size,
204 PyObject *value_fast,
205 const int *dims,
206 const int dims_len,
207 const PyTypeObject *type,
208 const char *error_prefix)
209{
210 const Py_ssize_t value_len = PySequence_Fast_GET_SIZE(value_fast);
211 const int length = dims[0];
212
213 if (dims_len == 1) {
214 if (PyC_AsArray_FAST(*array_p, array_item_size, value_fast, length, type, error_prefix) == -1)
215 {
216 return -1;
217 }
218 *array_p = POINTER_OFFSET(*array_p, array_item_size * length);
219 }
220 else {
221 if (value_len != length) {
222 PyErr_Format(PyExc_TypeError,
223 "%.200s: invalid sequence length. expected %d, got %d",
224 error_prefix,
225 length,
226 value_len);
227 return -1;
228 }
229
230 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
231 const int *dims_next = dims + 1;
232 const int dims_next_len = dims_len - 1;
233
234 for (int i = 0; i < length; i++) {
235 if (PyC_AsArray_Multi_impl(array_p,
236 array_item_size,
237 value_fast_items[i],
238 dims_next,
239 dims_next_len,
240 type,
241 error_prefix) == -1)
242 {
243 return -1;
244 }
245 }
246 }
247 return 0;
248}
249
250static int PyC_AsArray_Multi_impl(void **array_p,
251 const size_t array_item_size,
252 PyObject *value,
253 const int *dims,
254 const int dims_len,
255 const PyTypeObject *type,
256 const char *error_prefix)
257{
258 PyObject *value_fast;
259 int ret;
260
261 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
262 return -1;
263 }
264
266 array_p, array_item_size, value_fast, dims, dims_len, type, error_prefix);
267 Py_DECREF(value_fast);
268 return ret;
269}
270
272 const size_t array_item_size,
273 PyObject *value_fast,
274 const int *dims,
275 const int dims_len,
276 const PyTypeObject *type,
277 const char *error_prefix)
278{
280 &array, array_item_size, value_fast, dims, dims_len, type, error_prefix);
281}
282
284 const size_t array_item_size,
285 PyObject *value,
286 const int *dims,
287 const int dims_len,
288 const PyTypeObject *type,
289 const char *error_prefix)
290{
292 &array, array_item_size, value, dims, dims_len, type, error_prefix);
293}
294
296
297/* -------------------------------------------------------------------- */
302
303PyObject *PyC_Tuple_PackArray_F32(const float *array, uint len)
304{
305 PyObject *tuple = PyTuple_New(len);
306 for (uint i = 0; i < len; i++) {
307 PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
308 }
309 return tuple;
310}
311
312PyObject *PyC_Tuple_PackArray_F64(const double *array, uint len)
313{
314 PyObject *tuple = PyTuple_New(len);
315 for (uint i = 0; i < len; i++) {
316 PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
317 }
318 return tuple;
319}
320
321PyObject *PyC_Tuple_PackArray_I32(const int *array, uint len)
322{
323 PyObject *tuple = PyTuple_New(len);
324 for (uint i = 0; i < len; i++) {
325 PyTuple_SET_ITEM(tuple, i, PyLong_FromLong(array[i]));
326 }
327 return tuple;
328}
329
331{
332 PyObject *tuple = PyTuple_New(len);
333 for (uint i = 0; i < len; i++) {
334 PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
335 }
336 return tuple;
337}
338
339PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len)
340{
341 PyObject *tuple = PyTuple_New(len);
342 for (uint i = 0; i < len; i++) {
343 PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
344 }
345 return tuple;
346}
347
348PyObject *PyC_Tuple_PackArray_String(const char **array, uint len)
349{
350 /* Not part of numeric array packing but useful none the less. */
351 PyObject *tuple = PyTuple_New(len);
352 for (uint i = 0; i < len; i++) {
353 if (PyObject *value = PyUnicode_FromString(array[i])) {
354 PyTuple_SET_ITEM(tuple, i, value);
355 }
356 else {
357 Py_DECREF(tuple);
358 tuple = nullptr;
359 break;
360 }
361 }
362 return tuple;
363}
364
366
367/* -------------------------------------------------------------------- */
370
371static PyObject *PyC_Tuple_PackArray_Multi_F32_impl(const float **array_p,
372 const int dims[],
373 const int dims_len)
374{
375 const int len = dims[0];
376 if (dims_len == 1) {
377 PyObject *tuple = PyC_Tuple_PackArray_F32(*array_p, len);
378 *array_p = (*array_p) + len;
379 return tuple;
380 }
381 PyObject *tuple = PyTuple_New(dims[0]);
382 const int *dims_next = dims + 1;
383 const int dims_next_len = dims_len - 1;
384 for (uint i = 0; i < len; i++) {
385 PyTuple_SET_ITEM(
386 tuple, i, PyC_Tuple_PackArray_Multi_F32_impl(array_p, dims_next, dims_next_len));
387 }
388 return tuple;
389}
390PyObject *PyC_Tuple_PackArray_Multi_F32(const float *array, const int dims[], const int dims_len)
391{
392 return PyC_Tuple_PackArray_Multi_F32_impl(&array, dims, dims_len);
393}
394
395static PyObject *PyC_Tuple_PackArray_Multi_F64_impl(const double **array_p,
396 const int dims[],
397 const int dims_len)
398{
399 const int len = dims[0];
400 if (dims_len == 1) {
401 PyObject *tuple = PyC_Tuple_PackArray_F64(*array_p, len);
402 *array_p = (*array_p) + len;
403 return tuple;
404 }
405 PyObject *tuple = PyTuple_New(dims[0]);
406 const int *dims_next = dims + 1;
407 const int dims_next_len = dims_len - 1;
408 for (uint i = 0; i < len; i++) {
409 PyTuple_SET_ITEM(
410 tuple, i, PyC_Tuple_PackArray_Multi_F64_impl(array_p, dims_next, dims_next_len));
411 }
412 return tuple;
413}
414PyObject *PyC_Tuple_PackArray_Multi_F64(const double *array, const int dims[], const int dims_len)
415{
416 return PyC_Tuple_PackArray_Multi_F64_impl(&array, dims, dims_len);
417}
418
419static PyObject *PyC_Tuple_PackArray_Multi_I32_impl(const int **array_p,
420 const int dims[],
421 const int dims_len)
422{
423 const int len = dims[0];
424 if (dims_len == 1) {
425 PyObject *tuple = PyC_Tuple_PackArray_I32(*array_p, len);
426 *array_p = (*array_p) + len;
427 return tuple;
428 }
429 PyObject *tuple = PyTuple_New(dims[0]);
430 const int *dims_next = dims + 1;
431 const int dims_next_len = dims_len - 1;
432 for (uint i = 0; i < len; i++) {
433 PyTuple_SET_ITEM(
434 tuple, i, PyC_Tuple_PackArray_Multi_I32_impl(array_p, dims_next, dims_next_len));
435 }
436 return tuple;
437}
438PyObject *PyC_Tuple_PackArray_Multi_I32(const int *array, const int dims[], const int dims_len)
439{
440 return PyC_Tuple_PackArray_Multi_I32_impl(&array, dims, dims_len);
441}
442
443static PyObject *PyC_Tuple_PackArray_Multi_Bool_impl(const bool **array_p,
444 const int dims[],
445 const int dims_len)
446{
447 const int len = dims[0];
448 if (dims_len == 1) {
449 PyObject *tuple = PyC_Tuple_PackArray_Bool(*array_p, len);
450 *array_p = (*array_p) + len;
451 return tuple;
452 }
453 PyObject *tuple = PyTuple_New(dims[0]);
454 const int *dims_next = dims + 1;
455 const int dims_next_len = dims_len - 1;
456 for (uint i = 0; i < len; i++) {
457 PyTuple_SET_ITEM(
458 tuple, i, PyC_Tuple_PackArray_Multi_Bool_impl(array_p, dims_next, dims_next_len));
459 }
460 return tuple;
461}
462PyObject *PyC_Tuple_PackArray_Multi_Bool(const bool *array, const int dims[], const int dims_len)
463{
464 return PyC_Tuple_PackArray_Multi_Bool_impl(&array, dims, dims_len);
465}
466
468
469/* -------------------------------------------------------------------- */
472
473void PyC_Tuple_Fill(PyObject *tuple, PyObject *value)
474{
475 const uint tot = PyTuple_GET_SIZE(tuple);
476 uint i;
477
478 for (i = 0; i < tot; i++) {
479 PyTuple_SET_ITEM(tuple, i, value);
480 Py_INCREF(value);
481 }
482}
483
484void PyC_List_Fill(PyObject *list, PyObject *value)
485{
486 const uint tot = PyList_GET_SIZE(list);
487 uint i;
488
489 for (i = 0; i < tot; i++) {
490 PyList_SET_ITEM(list, i, value);
491 Py_INCREF(value);
492 }
493}
494
496
497/* -------------------------------------------------------------------- */
500
501int PyC_ParseBool(PyObject *o, void *p)
502{
503 bool *bool_p = static_cast<bool *>(p);
504 long value;
505 if (((value = PyLong_AsLong(o)) == -1) || !ELEM(value, 0, 1)) {
506 PyErr_Format(PyExc_ValueError, "expected a bool or int (0/1), got %s", Py_TYPE(o)->tp_name);
507 return 0;
508 }
509
510 *bool_p = value ? true : false;
511 return 1;
512}
513
514int PyC_ParseTypeOrNone(PyObject *o, void *p)
515{
516 PyC_TypeOrNone *data = static_cast<PyC_TypeOrNone *>(p);
517 if (o == Py_None) {
518 *data->value_p = nullptr;
519 return 1;
520 }
521 if (!PyObject_TypeCheck(o, data->type)) {
522 PyErr_Format(PyExc_TypeError,
523 "expected %.200s or None, not %.200s",
524 data->type->tp_name,
525 Py_TYPE(o)->tp_name);
526 return 0;
527 }
528 *data->value_p = o;
529 return 1;
530}
531
532int PyC_ParseOptionalInt(PyObject *o, void *p)
533{
534 std::optional<int> *value_p = static_cast<std::optional<int> *>(p);
535 if (o == Py_None) {
536 value_p->reset();
537 return 1;
538 }
539 const int value = PyC_Long_AsI32(o);
540 if (value == -1 && PyErr_Occurred()) {
541 return 0;
542 }
543 *value_p = value;
544 return 1;
545}
546
547int PyC_ParseOptionalDouble(PyObject *o, void *p)
548{
549 std::optional<double> *value_p = static_cast<std::optional<double> *>(p);
550 if (o == Py_None) {
551 value_p->reset();
552 return 1;
553 }
554 const double value = PyFloat_AsDouble(o);
555 if (value == -1.0 && PyErr_Occurred()) {
556 return 0;
557 }
558 *value_p = value;
559 return 1;
560}
561
562int PyC_ParseOptionalFloat(PyObject *o, void *p)
563{
564 std::optional<float> *value_p = static_cast<std::optional<float> *>(p);
565 if (o == Py_None) {
566 value_p->reset();
567 return 1;
568 }
569 const double value = PyFloat_AsDouble(o);
570 if (value == -1.0 && PyErr_Occurred()) {
571 return 0;
572 }
573 *value_p = float(value);
574 return 1;
575}
576
577int PyC_ParseOptionalUInt(PyObject *o, void *p)
578{
579 std::optional<uint> *value_p = static_cast<std::optional<uint> *>(p);
580 if (o == Py_None) {
581 value_p->reset();
582 return 1;
583 }
584 const uint value = PyC_Long_AsU32(o);
585 if (value == uint(-1) && PyErr_Occurred()) {
586 return 0;
587 }
588 *value_p = value;
589 return 1;
590}
591
592int PyC_ParseOptionalBool(PyObject *o, void *p)
593{
594 std::optional<bool> *value_p = static_cast<std::optional<bool> *>(p);
595 if (o == Py_None) {
596 value_p->reset();
597 return 1;
598 }
599 long value;
600 if (((value = PyLong_AsLong(o)) == -1) || !ELEM(value, 0, 1)) {
601 PyErr_Format(
602 PyExc_ValueError, "expected a bool, int (0/1), or None, got %s", Py_TYPE(o)->tp_name);
603 return 0;
604 }
605 *value_p = value ? true : false;
606 return 1;
607}
608
609int PyC_ParseRectI(PyObject *o, void *p)
610{
611 rcti *rect = static_cast<rcti *>(p);
612 if (!PyArg_ParseTuple(o,
613 "(ii)" /* `min` */
614 "(ii)" /* `max` */
615 ":rect",
616 &rect->xmin,
617 &rect->ymin,
618 &rect->xmax,
619 &rect->ymax))
620 {
621 return 0;
622 }
623 return 1;
624}
625
626int PyC_ParseOptionalRectI(PyObject *o, void *p)
627{
628 std::optional<rcti> *value_p = static_cast<std::optional<rcti> *>(p);
629 if (o == Py_None) {
630 value_p->reset();
631 return 1;
632 }
633 rcti rect;
634 if (!PyC_ParseRectI(o, &rect)) {
635 return 0;
636 }
637 *value_p = rect;
638 return 1;
639}
640
641int PyC_ParseStringEnum(PyObject *o, void *p)
642{
643 PyC_StringEnum *e = static_cast<PyC_StringEnum *>(p);
644 const char *value = PyUnicode_AsUTF8(o);
645 if (value == nullptr) {
646 PyErr_Format(PyExc_ValueError, "expected a string, got %s", Py_TYPE(o)->tp_name);
647 return 0;
648 }
649 int i;
650 for (i = 0; e->items[i].id; i++) {
651 if (STREQ(e->items[i].id, value)) {
652 e->value_found = e->items[i].value;
653 return 1;
654 }
655 }
656
657 /* Set as a precaution. */
658 e->value_found = -1;
659
660 PyObject *enum_items = PyTuple_New(i);
661 for (i = 0; e->items[i].id; i++) {
662 PyTuple_SET_ITEM(enum_items, i, PyUnicode_FromString(e->items[i].id));
663 }
664 PyErr_Format(PyExc_ValueError, "expected a string in %S, got '%s'", enum_items, value);
665 Py_DECREF(enum_items);
666 return 0;
667}
668
669const char *PyC_StringEnum_FindIDFromValue(const PyC_StringEnumItems *items, const int value)
670{
671 for (int i = 0; items[i].id; i++) {
672 if (items[i].value == value) {
673 return items[i].id;
674 }
675 }
676 return nullptr;
677}
678
679int PyC_CheckArgs_DeepCopy(PyObject *args)
680{
681 PyObject *dummy_pydict;
682 return PyArg_ParseTuple(args,
683 "|" /* Optional arguments. */
684 "O!" /* `memo` */
685 ":__deepcopy__",
686 &PyDict_Type,
687 &dummy_pydict) != 0;
688}
689
691
692#ifndef MATH_STANDALONE
693
694/* -------------------------------------------------------------------- */
699
700void PyC_ObSpit(const char *name, PyObject *var)
701{
702 const char *null_str = "<null>";
703 fprintf(stderr, "<%s> : ", name);
704 if (var == nullptr) {
705 fprintf(stderr, "%s\n", null_str);
706 }
707 else {
708 PyObject_Print(var, stderr, 0);
709 const PyTypeObject *type = Py_TYPE(var);
710 fprintf(stderr,
711 " ref:%d, ptr:%p, type: %s\n",
712 int(var->ob_refcnt),
713 static_cast<void *>(var),
714 type ? type->tp_name : null_str);
715 }
716}
717
718void PyC_ObSpitStr(char *result, size_t result_maxncpy, PyObject *var)
719{
720 /* No name, creator of string can manage that. */
721 const char *null_str = "<null>";
722 if (var == nullptr) {
723 BLI_strncpy_utf8(result, null_str, result_maxncpy);
724 }
725 else {
726 const PyTypeObject *type = Py_TYPE(var);
727 PyObject *var_str = PyObject_Repr(var);
728 if (var_str == nullptr) {
729 /* We could print error here,
730 * but this may be used for generating errors - so don't for now. */
731 PyErr_Clear();
732 }
734 result_maxncpy,
735 " ref=%d, ptr=%p, type=%s, value=%.200s",
736 int(var->ob_refcnt),
737 static_cast<void *>(var),
738 type ? type->tp_name : null_str,
739 var_str ? PyUnicode_AsUTF8(var_str) : "<error>");
740 if (var_str != nullptr) {
741 Py_DECREF(var_str);
742 }
743 }
744}
745
747{
748
749 const char *filename;
750 int lineno;
751
752 /* NOTE: allow calling from outside python (RNA). */
754 fprintf(stderr, "Python line lookup failed, interpreter inactive\n");
755 return;
756 }
757
758 PyErr_Clear();
759 PyC_FileAndNum(&filename, &lineno);
760
761 fprintf(stderr, "%s:%d\n", filename, lineno);
762}
763
765{
766 /* NOTE: allow calling from outside python (RNA). */
768 fprintf(stderr, "Python line lookup failed, interpreter inactive\n");
769 return;
770 }
771
772 /* lame but handy */
773 const PyGILState_STATE gilstate = PyGILState_Ensure();
774 PyRun_SimpleString("__import__('traceback').print_stack()");
775 PyGILState_Release(gilstate);
776}
777
779
780/* -------------------------------------------------------------------- */
783
784void PyC_FileAndNum(const char **r_filename, int *r_lineno)
785{
786 PyFrameObject *frame;
787 PyCodeObject *code;
788
789 if (r_filename) {
790 *r_filename = nullptr;
791 }
792 if (r_lineno) {
793 *r_lineno = -1;
794 }
795
796 if (!(frame = PyEval_GetFrame())) {
797 return;
798 }
799 if (!(code = PyFrame_GetCode(frame))) {
800 return;
801 }
802
803 /* when executing a script */
804 if (r_filename) {
805 *r_filename = PyUnicode_AsUTF8(code->co_filename);
806 }
807
808 /* when executing a module */
809 if (r_filename && *r_filename == nullptr) {
810 /* try an alternative method to get the r_filename - module based
811 * references below are all borrowed (double checked) */
812 PyObject *mod_name = PyDict_GetItemString(PyEval_GetGlobals(), "__name__");
813 if (mod_name) {
814 PyObject *mod = PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
815 if (mod) {
816 PyObject *mod_file = PyModule_GetFilenameObject(mod);
817 if (mod_file) {
818 *r_filename = PyUnicode_AsUTF8(mod_name);
819 Py_DECREF(mod_file);
820 }
821 else {
822 PyErr_Clear();
823 }
824 }
825
826 /* unlikely, fallback */
827 if (*r_filename == nullptr) {
828 *r_filename = PyUnicode_AsUTF8(mod_name);
829 }
830 }
831 }
832
833 if (r_lineno) {
834 *r_lineno = PyFrame_GetLineNumber(frame);
835 }
836
837 Py_DECREF(code);
838}
839
840void PyC_FileAndNum_Safe(const char **r_filename, int *r_lineno)
841{
843 return;
844 }
845
846 PyC_FileAndNum(r_filename, r_lineno);
847}
848
850
851/* -------------------------------------------------------------------- */
854
855PyObject *PyC_FrozenSetFromStrings(const char **strings)
856{
857 const char **str;
858 PyObject *ret;
859
860 ret = PyFrozenSet_New(nullptr);
861
862 for (str = strings; *str; str++) {
863 PyObject *py_str = PyUnicode_FromString(*str);
864 PySet_Add(ret, py_str);
865 Py_DECREF(py_str);
866 }
867
868 return ret;
869}
870
872
873/* -------------------------------------------------------------------- */
876
877PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...)
878{
879 PyObject *error_value_as_unicode = nullptr;
880
881 if (PyErr_Occurred()) {
882 PyObject *error_type, *error_value, *error_traceback;
883 PyErr_Fetch(&error_type, &error_value, &error_traceback);
884
885 if (PyUnicode_Check(error_value)) {
886 error_value_as_unicode = error_value;
887 Py_INCREF(error_value_as_unicode);
888 }
889 else {
890 error_value_as_unicode = PyUnicode_FromFormat(
891 "%.200s(%S)", Py_TYPE(error_value)->tp_name, error_value);
892 }
893 PyErr_Restore(error_type, error_value, error_traceback);
894 }
895
896 va_list args;
897
898 va_start(args, format);
899 PyObject *error_value_format = PyUnicode_FromFormatV(format, args); /* Can fail and be null. */
900 va_end(args);
901
902 if (error_value_as_unicode) {
903 if (error_value_format) {
904 PyObject *error_value_format_prev = error_value_format;
905 error_value_format = PyUnicode_FromFormat(
906 "%S, %S", error_value_format, error_value_as_unicode);
907 Py_DECREF(error_value_format_prev);
908 }
909 else {
910 /* Should never happen, hints at incorrect API use or memory corruption. */
911 error_value_format = PyUnicode_FromFormat("(internal error), %S", error_value_as_unicode);
912 }
913 Py_DECREF(error_value_as_unicode);
914 }
915
916 PyErr_SetObject(exception_type_prefix, error_value_format);
917 Py_XDECREF(error_value_format);
918
919 /* Strange to always return null, matches #PyErr_Format. */
920 return nullptr;
921}
922
923PyObject *PyC_Err_SetString_Prefix(PyObject *exception_type_prefix, const char *str)
924{
925 return PyC_Err_Format_Prefix(exception_type_prefix, "%s", str);
926}
927
928void PyC_Err_PrintWithFunc(PyObject *py_func)
929{
930 /* since we return to C code we can't leave the error */
931 PyCodeObject *f_code = reinterpret_cast<PyCodeObject *>(PyFunction_GET_CODE(py_func));
932 PyErr_Print();
933
934 /* use py style error */
935 fprintf(stderr,
936 "File \"%s\", line %d, in %s\n",
937 PyUnicode_AsUTF8(f_code->co_filename),
938 f_code->co_firstlineno,
939 PyUnicode_AsUTF8((reinterpret_cast<PyFunctionObject *>(py_func))->func_name));
940}
941
943
944/* -------------------------------------------------------------------- */
947
951static std::optional<int> g_system_exit_code;
952std::optional<int> PyC_ExceptionSystemExitCode()
953{
954 return g_system_exit_code;
955}
956
958{
959 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
960 return false;
961 }
962
963 /* Get exit code and put back exception. */
964 PyObject *exc_obj = PyErr_GetRaisedException();
965 PyObject *code_obj = ((PySystemExitObject *)exc_obj)->code;
967 if (code_obj && code_obj != Py_None) {
968 g_system_exit_code = PyLong_Check(code_obj) ? int(PyLong_AsLong(code_obj)) : 1;
969 }
970 PyErr_SetRaisedException(exc_obj);
971 return true;
972}
973
991{
993 return;
994 }
995 /* Inspecting, follow Python's logic in #_Py_HandleSystemExit & treat as a regular exception. */
996# if 0 /* FIXME: */
997 if (_Py_GetConfig()->inspect) {
998 return;
999 }
1000# endif
1001
1002 /* NOTE(@ideasman42): A `SystemExit` exception will exit immediately (unless inspecting).
1003 * So print the error and exit now. Without this #PyErr_Display shows the error stack-trace
1004 * as a regular exception (as if something went wrong) and fail to exit.
1005 * see: #99966 for additional context.
1006 *
1007 * Arguably accessing a `SystemExit` exception as a buffer should be supported without exiting.
1008 * (by temporarily enabling inspection for example) however - it's not obvious exactly when this
1009 * should be enabled and complicates the Python API by introducing different kinds of execution.
1010 * Since the rule of thumb is for Blender's embedded Python to match stand-alone Python,
1011 * favor exiting when a `SystemExit` is raised.
1012 * Especially since this exception more likely to be used for background/batch-processing
1013 * utilities where exiting immediately makes sense, the possibility of this being called
1014 * indirectly from python-drivers or modal-operators is less of a concern. */
1015 PyErr_Print();
1016}
1017
1019{
1020 BLI_assert(PyErr_Occurred());
1021
1023
1024 /* The resulting exception as a string (return value). */
1025 PyObject *result = nullptr;
1026
1027 PyObject *error_type, *error_value, *error_traceback;
1028 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1029
1030 /* Normalizing is needed because it's possible the error value is a string which
1031 * #PyErr_Display will fail to print. */
1032 PyErr_NormalizeException(&error_type, &error_value, &error_traceback);
1033
1034 /* `io.StringIO()`. */
1035 PyObject *string_io = nullptr;
1036 PyObject *string_io_mod = nullptr;
1037 PyObject *string_io_getvalue = nullptr;
1038 if ((string_io_mod = PyImport_ImportModule("io")) &&
1039 (string_io = PyObject_CallMethod(string_io_mod, "StringIO", nullptr)) &&
1040 (string_io_getvalue = PyObject_GetAttrString(string_io, "getvalue")))
1041 {
1042 PyObject *stderr_backup = PySys_GetObject("stderr"); /* Borrowed. */
1043 /* Since these were borrowed we don't want them freed when replaced. */
1044 Py_INCREF(stderr_backup);
1045 PySys_SetObject("stderr", string_io); /* Freed when overwriting. */
1046
1047 PyErr_Display(error_type, error_value, error_traceback);
1048
1049 result = PyObject_CallObject(string_io_getvalue, nullptr);
1050 PySys_SetObject("stderr", stderr_backup);
1051 Py_DECREF(stderr_backup); /* Now `sys` owns the reference again. */
1052 }
1053 else {
1054 PySys_WriteStderr("Internal error creating: io.StringIO()!\n");
1055 if (PyErr_Occurred()) [[unlikely]] {
1056 PyErr_Print(); /* Show the error accessing `io.StringIO`. */
1057 }
1058 PyErr_Display(error_type, error_value, error_traceback);
1059 }
1060
1061 Py_XDECREF(string_io_mod);
1062 Py_XDECREF(string_io_getvalue);
1063 Py_XDECREF(string_io); /* Free the original reference. */
1064
1065 if (result == nullptr) {
1066 result = PyObject_Str(error_value);
1067 /* Python does this too. */
1068 if (result == nullptr) [[unlikely]] {
1069 result = PyUnicode_FromFormat("<unprintable %s object>", Py_TYPE(error_value)->tp_name);
1070 }
1071 }
1072
1073 PyErr_Restore(error_type, error_value, error_traceback);
1074
1075 return result;
1076}
1077
1079{
1080 BLI_assert(PyErr_Occurred());
1081
1083
1084 /* The resulting exception as a string (return value). */
1085 PyObject *result = nullptr;
1086
1087 PyObject *error_type, *error_value, *error_traceback;
1088
1089 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1090
1091 if (PyErr_GivenExceptionMatches(error_type, PyExc_SyntaxError)) {
1092 /* Special exception for syntax errors,
1093 * in these cases the full error is verbose and not very useful,
1094 * just use the initial text so we know what the error is. */
1095 if (PyTuple_CheckExact(error_value) && PyTuple_GET_SIZE(error_value) >= 1) {
1096 result = PyObject_Str(PyTuple_GET_ITEM(error_value, 0));
1097 }
1098 }
1099
1100 if (result == nullptr) {
1101 result = PyObject_Str(error_value);
1102 /* Python does this too. */
1103 if (result == nullptr) [[unlikely]] {
1104 result = PyUnicode_FromFormat("<unprintable %s object>", Py_TYPE(error_value)->tp_name);
1105 }
1106 }
1107
1108 PyErr_Restore(error_type, error_value, error_traceback);
1109
1110 return result;
1111}
1112
1114
1115/* -------------------------------------------------------------------- */
1120
1121const char *PyC_UnicodeAsBytesAndSize(PyObject *py_str, Py_ssize_t *r_size, PyObject **r_coerce)
1122{
1123 const char *result;
1124
1125 result = PyUnicode_AsUTF8AndSize(py_str, r_size);
1126
1127 if (result) {
1128 /* 99% of the time this is enough but we better support non unicode
1129 * chars since blender doesn't limit this */
1130 return result;
1131 }
1132
1133 PyErr_Clear();
1134
1135 if (PyBytes_Check(py_str)) {
1136 *r_size = PyBytes_GET_SIZE(py_str);
1137 return PyBytes_AS_STRING(py_str);
1138 }
1139 if ((*r_coerce = PyUnicode_EncodeFSDefault(py_str))) {
1140 *r_size = PyBytes_GET_SIZE(*r_coerce);
1141 return PyBytes_AS_STRING(*r_coerce);
1142 }
1143
1144 /* leave error raised from EncodeFS */
1145 return nullptr;
1146}
1147
1148const char *PyC_UnicodeAsBytes(PyObject *py_str, PyObject **r_coerce)
1149{
1150 const char *result;
1151
1152 result = PyUnicode_AsUTF8(py_str);
1153
1154 if (result) {
1155 /* 99% of the time this is enough but we better support non unicode
1156 * chars since blender doesn't limit this. */
1157 return result;
1158 }
1159
1160 PyErr_Clear();
1161
1162 if (PyBytes_Check(py_str)) {
1163 return PyBytes_AS_STRING(py_str);
1164 }
1165 if ((*r_coerce = PyUnicode_EncodeFSDefault(py_str))) {
1166 return PyBytes_AS_STRING(*r_coerce);
1167 }
1168
1169 /* leave error raised from EncodeFS */
1170 return nullptr;
1171}
1172
1173PyObject *PyC_UnicodeFromBytesAndSize(const char *str, Py_ssize_t size)
1174{
1175 PyObject *result = PyUnicode_FromStringAndSize(str, size);
1176 if (result) {
1177 /* 99% of the time this is enough but we better support non unicode
1178 * chars since blender doesn't limit this */
1179 return result;
1180 }
1181
1182 PyErr_Clear();
1183 /* this means paths will always be accessible once converted, on all OS's */
1184 result = PyUnicode_DecodeFSDefaultAndSize(str, size);
1185 return result;
1186}
1187
1188PyObject *PyC_UnicodeFromBytes(const char *str)
1189{
1190 return PyC_UnicodeFromBytesAndSize(str, strlen(str));
1191}
1192
1193PyObject *PyC_UnicodeFromStdStr(const std::string &str)
1194{
1195 return PyC_UnicodeFromBytesAndSize(str.c_str(), str.length());
1196}
1197
1198int PyC_ParseUnicodeAsBytesAndSize(PyObject *o, void *p)
1199{
1201 if (o == nullptr) [[unlikely]] {
1202 /* Signal to cleanup. */
1203 Py_CLEAR(data->value_coerce);
1204 return 1;
1205 }
1206 /* The value must be cleared. */
1207 BLI_assert(!(data->value_coerce || data->value || data->value_len));
1208 data->value = PyC_UnicodeAsBytesAndSize(o, &data->value_len, &data->value_coerce);
1209 if (data->value == nullptr) {
1210 /* Leave the error as-is. */
1211 return 0;
1212 }
1213 /* Needed to #Py_DECREF `data->value_coerce` on future failure. */
1214 return data->value_coerce ? Py_CLEANUP_SUPPORTED : 1;
1215}
1216
1218{
1219 if (o == Py_None) {
1221 BLI_assert(!(data->value_coerce || data->value || data->value_len));
1223 return 1;
1224 }
1225 return PyC_ParseUnicodeAsBytesAndSize(o, p);
1226}
1227
1229
1230/* -------------------------------------------------------------------- */
1233
1234PyObject *PyC_DefaultNameSpace(const char *filename)
1235{
1236 PyObject *modules = PyImport_GetModuleDict();
1237 PyObject *builtins = PyEval_GetBuiltins();
1238 PyObject *mod_main = PyModule_New("__main__");
1239 PyDict_SetItemString(modules, "__main__", mod_main);
1240 Py_DECREF(mod_main); /* `sys.modules` owns now. */
1241 PyModule_AddStringConstant(mod_main, "__name__", "__main__");
1242
1243 /* This won't map to a real file when executing text-blocks and buttons.
1244 * In this case an identifier is typically used that is surrounded by angle-brackets.
1245 * It's mainly helpful for the UI and messages to show *something*. */
1246 PyModule_AddObject(mod_main, "__file__", PyC_UnicodeFromBytes(filename));
1247 PyModule_AddObjectRef(mod_main, "__builtins__", builtins);
1248
1249 return PyModule_GetDict(mod_main);
1250}
1251
1252bool PyC_NameSpace_ImportArray(PyObject *py_dict, const char *imports[])
1253{
1254 for (int i = 0; imports[i]; i++) {
1255 PyObject *name = PyUnicode_FromString(imports[i]);
1256 PyObject *mod = PyImport_ImportModuleLevelObject(name, nullptr, nullptr, nullptr, 0);
1257 bool ok = false;
1258 if (mod) {
1259 PyDict_SetItem(py_dict, name, mod);
1260 ok = true;
1261 Py_DECREF(mod);
1262 }
1263 Py_DECREF(name);
1264
1265 if (!ok) {
1266 return false;
1267 }
1268 }
1269 return true;
1270}
1271
1273{
1274 PyObject *modules = PyImport_GetModuleDict();
1275 PyObject *main_mod = PyDict_GetItemString(modules, "__main__");
1276 if (main_mod) {
1277 /* Ensure the backed up module is kept until it's ownership */
1278 /* is transferred back to `sys.modules`. */
1279 Py_INCREF(main_mod);
1280 }
1281 return main_mod;
1282}
1283
1284void PyC_MainModule_Restore(PyObject *main_mod)
1285{
1286 PyObject *modules = PyImport_GetModuleDict();
1287 if (main_mod) {
1288 PyDict_SetItemString(modules, "__main__", main_mod);
1289 Py_DECREF(main_mod);
1290 }
1291 else {
1292 PyDict_DelItemString(modules, "__main__");
1293 }
1294}
1295
1296int PyC_Module_AddToSysModules(PyObject *sys_modules, PyObject *module)
1297{
1298 /* It would be OK to remove this assert if we ever wanted to add to a non-standard module dict.
1299 * Currently it's only ever expected that they match, hence the assert. */
1300 BLI_assert(sys_modules == PyImport_GetModuleDict());
1301 PyObject *name = PyModule_GetNameObject(module);
1302 if (name == nullptr) {
1303 return -1;
1304 }
1305 int result = PyDict_SetItem(sys_modules, name, module);
1306 Py_DECREF(name);
1307 return result;
1308}
1309
1311{
1312 /* instead of PyThreadState_Get, which calls Py_FatalError */
1313 return (PyThreadState_GetDict() != nullptr);
1314}
1315
1317
1318/* -------------------------------------------------------------------- */
1321
1322void PyC_RunQuicky(const char *filepath, int n, ...)
1323{
1324 /* NOTE: Would be nice if python had this built in
1325 * See: https://developer.blender.org/docs/handbook/tooling/pyfromc/ */
1326
1327 FILE *fp = fopen(filepath, "r");
1328
1329 if (fp) {
1330 const PyGILState_STATE gilstate = PyGILState_Ensure();
1331
1332 va_list vargs;
1333
1334 Py_ssize_t *sizes = static_cast<Py_ssize_t *>(PyMem_MALLOC(sizeof(*sizes) * (n / 2)));
1335 int i;
1336
1337 PyObject *py_dict = PyC_DefaultNameSpace(filepath);
1338 PyObject *values = PyList_New(n / 2); /* namespace owns this, don't free */
1339
1340 PyObject *py_result, *ret;
1341
1342 PyObject *struct_mod = PyImport_ImportModule("struct");
1343 PyObject *calcsize = PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
1344 PyObject *pack = PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
1345 PyObject *unpack = PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */
1346
1347 Py_DECREF(struct_mod);
1348
1349 va_start(vargs, n);
1350 for (i = 0; i * 2 < n; i++) {
1351 const char *format = va_arg(vargs, char *);
1352 void *ptr = va_arg(vargs, void *);
1353
1354 ret = PyObject_CallFunction(calcsize, "s", format);
1355
1356 if (ret) {
1357 sizes[i] = PyLong_AsLong(ret);
1358 Py_DECREF(ret);
1359 ret = PyObject_CallFunction(unpack, "sy#", format, static_cast<char *>(ptr), sizes[i]);
1360 }
1361
1362 if (ret == nullptr) {
1363 printf("%s error, line:%d\n", __func__, __LINE__);
1364 PyErr_Print();
1365
1366 PyList_SET_ITEM(values, i, Py_NewRef(Py_None)); /* hold user */
1367
1368 sizes[i] = 0;
1369 }
1370 else {
1371 if (PyTuple_GET_SIZE(ret) == 1) {
1372 /* convenience, convert single tuples into single values */
1373 PyObject *tmp = PyTuple_GET_ITEM(ret, 0);
1374 Py_INCREF(tmp);
1375 Py_DECREF(ret);
1376 ret = tmp;
1377 }
1378
1379 PyList_SET_ITEM(values, i, ret); /* hold user */
1380 }
1381 }
1382 va_end(vargs);
1383
1384 /* set the value so we can access it */
1385 PyDict_SetItemString(py_dict, "values", values);
1386 Py_DECREF(values);
1387
1388 py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);
1389
1390 fclose(fp);
1391
1392 if (py_result) {
1393 /* don't use the result */
1394 Py_DECREF(py_result);
1395 py_result = nullptr;
1396
1397 /* we could skip this but then only slice assignment would work
1398 * better not be so strict */
1399 values = PyDict_GetItemString(py_dict, "values");
1400
1401 if (values && PyList_Check(values)) {
1402
1403 /* now get the values back */
1404 va_start(vargs, n);
1405 for (i = 0; i * 2 < n; i++) {
1406 const char *format = va_arg(vargs, char *);
1407 void *ptr = va_arg(vargs, void *);
1408
1409 PyObject *item;
1410 PyObject *item_new;
1411 /* prepend the string formatting and remake the tuple */
1412 item = PyList_GET_ITEM(values, i);
1413 if (PyTuple_CheckExact(item)) {
1414 int ofs = PyTuple_GET_SIZE(item);
1415 item_new = PyTuple_New(ofs + 1);
1416 while (ofs--) {
1417 PyObject *member = PyTuple_GET_ITEM(item, ofs);
1418 PyTuple_SET_ITEM(item_new, ofs + 1, member);
1419 Py_INCREF(member);
1420 }
1421
1422 PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
1423 }
1424 else {
1425 item_new = Py_BuildValue("sO", format, item);
1426 }
1427
1428 ret = PyObject_Call(pack, item_new, nullptr);
1429
1430 if (ret) {
1431 /* copy the bytes back into memory */
1432 memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
1433 Py_DECREF(ret);
1434 }
1435 else {
1436 printf("%s error on arg '%d', line:%d\n", __func__, i, __LINE__);
1437 PyC_ObSpit("failed converting:", item_new);
1438 PyErr_Print();
1439 }
1440
1441 Py_DECREF(item_new);
1442 }
1443 va_end(vargs);
1444 }
1445 else {
1446 printf("%s error, 'values' not a list, line:%d\n", __func__, __LINE__);
1447 }
1448 }
1449 else {
1450 printf("%s error line:%d\n", __func__, __LINE__);
1451 PyErr_Print();
1452 }
1453
1454 Py_DECREF(calcsize);
1455 Py_DECREF(pack);
1456 Py_DECREF(unpack);
1457
1458 PyMem_FREE(sizes);
1459
1460 PyGILState_Release(gilstate);
1461 }
1462 else {
1463 fprintf(stderr, "%s: '%s' missing\n", __func__, filepath);
1464 }
1465}
1466
1467void *PyC_RNA_AsPointer(PyObject *value, const char *type_name)
1468{
1469 if (!STREQ(Py_TYPE(value)->tp_name, type_name)) {
1470 PyErr_Format(PyExc_TypeError,
1471 "expected '%.200s' type found '%.200s' instead",
1472 type_name,
1473 Py_TYPE(value)->tp_name);
1474 return nullptr;
1475 }
1476
1477 PyObject *as_pointer = PyObject_GetAttrString(value, "as_pointer");
1478 if ((as_pointer == nullptr) || !PyCallable_Check(as_pointer)) {
1479 Py_XDECREF(as_pointer);
1480 PyErr_Format(PyExc_TypeError, "Invalid %.200s pointer", type_name);
1481 return nullptr;
1482 }
1483
1484 /* Must be a `type_name` object. */
1485 PyObject *pointer = PyObject_CallObject(as_pointer, nullptr);
1486 Py_DECREF(as_pointer);
1487
1488 if (pointer == nullptr) {
1489 PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
1490 return nullptr;
1491 }
1492 void *result = PyLong_AsVoidPtr(pointer);
1493 Py_DECREF(pointer);
1494 if (!result) {
1495 PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
1496 }
1497
1498 return result;
1499}
1500
1502
1503/* -------------------------------------------------------------------- */
1508
1509PyObject *PyC_FlagSet_AsString(const PyC_FlagSet *item)
1510{
1511 PyObject *py_items = PyList_New(0);
1512 for (; item->identifier; item++) {
1513 PyList_APPEND(py_items, PyUnicode_FromString(item->identifier));
1514 }
1515 PyObject *py_string = PyObject_Repr(py_items);
1516 Py_DECREF(py_items);
1517 return py_string;
1518}
1519
1520int PyC_FlagSet_ValueFromID_int(const PyC_FlagSet *item, const char *identifier, int *r_value)
1521{
1522 for (; item->identifier; item++) {
1523 if (STREQ(item->identifier, identifier)) {
1524 *r_value = item->value;
1525 return 1;
1526 }
1527 }
1528
1529 return 0;
1530}
1531
1533 const char *identifier,
1534 int *r_value,
1535 const char *error_prefix)
1536{
1537 if (PyC_FlagSet_ValueFromID_int(item, identifier, r_value) == 0) {
1538 PyObject *enum_str = PyC_FlagSet_AsString(item);
1539 PyErr_Format(
1540 PyExc_ValueError, "%s: '%.200s' not found in (%U)", error_prefix, identifier, enum_str);
1541 Py_DECREF(enum_str);
1542 return -1;
1543 }
1544
1545 return 0;
1546}
1547
1549 PyObject *value,
1550 int *r_value,
1551 const char *error_prefix)
1552{
1553 /* set of enum items, concatenate all values with OR */
1554 int ret, flag = 0;
1555
1556 if (!PySet_Check(value)) {
1557 PyErr_Format(PyExc_TypeError,
1558 "%.200s expected a set, not %.200s",
1559 error_prefix,
1560 Py_TYPE(value)->tp_name);
1561 return -1;
1562 }
1563
1564 *r_value = 0;
1565
1566 if (PySet_GET_SIZE(value) > 0) {
1567 PyObject *it = PyObject_GetIter(value);
1568 PyObject *key;
1569 while ((key = PyIter_Next(it))) {
1570 /* Borrow from the set. */
1571 Py_DECREF(key);
1572
1573 const char *param = PyUnicode_AsUTF8(key);
1574 if (param == nullptr) {
1575 PyErr_Format(PyExc_TypeError,
1576 "%.200s set must contain strings, not %.200s",
1577 error_prefix,
1578 Py_TYPE(key)->tp_name);
1579 break;
1580 }
1581
1582 if (PyC_FlagSet_ValueFromID(items, param, &ret, error_prefix) < 0) {
1583 break;
1584 }
1585
1586 flag |= ret;
1587 }
1588 Py_DECREF(it);
1589 if (key != nullptr) {
1590 return -1;
1591 }
1592 }
1593
1594 *r_value = flag;
1595 return 0;
1596}
1597
1598PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag)
1599{
1600 PyObject *ret = PySet_New(nullptr);
1601 PyObject *pystr;
1602
1603 for (; items->identifier; items++) {
1604 if (items->value & flag) {
1605 pystr = PyUnicode_FromString(items->identifier);
1606 PySet_Add(ret, pystr);
1607 Py_DECREF(pystr);
1608 }
1609 }
1610
1611 return ret;
1612}
1613
1615
1616/* -------------------------------------------------------------------- */
1619
1620[[nodiscard]] static PyObject *pyc_run_string_as_py_object(const char *imports[],
1621 const char *imports_star[],
1622 const char *expr,
1623 const char *filename)
1624 ATTR_NONNULL(3, 4);
1625static PyObject *pyc_run_string_as_py_object(const char *imports[],
1626 const char *imports_star[],
1627 const char *expr,
1628 const char *filename)
1629{
1630 PyObject *main_mod = PyC_MainModule_Backup();
1631
1632 PyObject *py_dict = PyC_DefaultNameSpace(filename);
1633
1634 if (imports_star) {
1635 for (int i = 0; imports_star[i]; i++) {
1636 PyObject *mod = PyImport_ImportModule(imports_star[i]);
1637 if (mod) {
1638 /* Don't overwrite existing values (override=0). */
1639 PyDict_Merge(py_dict, PyModule_GetDict(mod), 0);
1640 Py_DECREF(mod);
1641 }
1642 else { /* Highly unlikely but possibly. */
1643 PyErr_Print();
1644 }
1645 }
1646 }
1647
1648 PyObject *retval;
1649 if (imports && !PyC_NameSpace_ImportArray(py_dict, imports)) {
1650 retval = nullptr; /* Failure. */
1651 }
1652 else {
1653 retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict);
1654 }
1655
1656 PyC_MainModule_Restore(main_mod);
1657
1658 return retval;
1659}
1660
1661bool PyC_RunString_AsNumber(const char *imports[],
1662 const char *expr,
1663 const char *filename,
1664 double *r_value)
1665{
1666 int ok = -1;
1667 const char *imports_star[] = {"math", nullptr};
1668 if (PyObject *retval = pyc_run_string_as_py_object(imports, imports_star, expr, filename)) {
1669 double val;
1670
1671 if (PyTuple_Check(retval)) {
1672 /* Users my have typed in `10km, 2m`, accumulate all values. */
1673 val = 0.0;
1674 for (int i = 0; i < PyTuple_GET_SIZE(retval); i++) {
1675 const double val_item = PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
1676 if (val_item == -1 && PyErr_Occurred()) {
1677 val = -1;
1678 break;
1679 }
1680 val += val_item;
1681 }
1682 }
1683 else {
1684 val = PyFloat_AsDouble(retval);
1685 }
1686 Py_DECREF(retval);
1687
1688 if (val == -1 && PyErr_Occurred()) {
1689 ok = false;
1690 }
1691 else if (!isfinite(val)) {
1692 *r_value = 0.0;
1693 ok = true;
1694 }
1695 else {
1696 *r_value = val;
1697 ok = true;
1698 }
1699 }
1700 else {
1701 ok = false;
1702 }
1703 BLI_assert(ok != -1);
1704 return bool(ok);
1705}
1706
1707bool PyC_RunString_AsIntPtr(const char *imports[],
1708 const char *expr,
1709 const char *filename,
1710 intptr_t *r_value)
1711{
1712 int ok = -1;
1713 if (PyObject *retval = pyc_run_string_as_py_object(imports, nullptr, expr, filename)) {
1714 const intptr_t val = intptr_t(PyLong_AsVoidPtr(retval));
1715 if (val == 0 && PyErr_Occurred()) {
1716 ok = false;
1717 }
1718 else {
1719 *r_value = val;
1720 ok = true;
1721 }
1722
1723 Py_DECREF(retval);
1724 }
1725 else {
1726 ok = false;
1727 }
1728 BLI_assert(ok != -1);
1729 return ok;
1730}
1731
1732bool PyC_RunString_AsStringAndSize(const char *imports[],
1733 const char *expr,
1734 const char *filename,
1735 char **r_value,
1736 size_t *r_value_size)
1737{
1738 int ok = -1;
1739 if (PyObject *retval = pyc_run_string_as_py_object(imports, nullptr, expr, filename)) {
1740 Py_ssize_t val_len;
1741 const char *val = PyUnicode_AsUTF8AndSize(retval, &val_len);
1742 if (val == nullptr && PyErr_Occurred()) {
1743 ok = false;
1744 }
1745 else {
1746 char *val_alloc = MEM_new_array_uninitialized<char>(size_t(val_len) + 1, __func__);
1747 memcpy(val_alloc, val, (size_t(val_len) + 1) * sizeof(*val_alloc));
1748 *r_value = val_alloc;
1749 *r_value_size = val_len;
1750 ok = true;
1751 }
1752 Py_DECREF(retval);
1753 }
1754 else {
1755 ok = false;
1756 }
1757 BLI_assert(ok != -1);
1758 return ok;
1759}
1760
1761bool PyC_RunString_AsString(const char *imports[],
1762 const char *expr,
1763 const char *filename,
1764 char **r_value)
1765{
1766 size_t value_size;
1767 return PyC_RunString_AsStringAndSize(imports, expr, filename, r_value, &value_size);
1768}
1769
1770bool PyC_RunString_AsStringAndSizeOrNone(const char *imports[],
1771 const char *expr,
1772 const char *filename,
1773 char **r_value,
1774 size_t *r_value_size)
1775{
1776 int ok = -1;
1777 if (PyObject *retval = pyc_run_string_as_py_object(imports, nullptr, expr, filename)) {
1778 if (retval == Py_None) {
1779 *r_value = nullptr;
1780 *r_value_size = 0;
1781 ok = true;
1782 }
1783 else {
1784 Py_ssize_t val_len;
1785 const char *val = PyUnicode_AsUTF8AndSize(retval, &val_len);
1786 if (val == nullptr && PyErr_Occurred()) {
1787 ok = false;
1788 }
1789 else {
1790 char *val_alloc = MEM_new_array_uninitialized<char>(size_t(val_len) + 1, __func__);
1791 memcpy(val_alloc, val, (size_t(val_len) + 1) * sizeof(*val_alloc));
1792 *r_value = val_alloc;
1793 *r_value_size = val_len;
1794 ok = true;
1795 }
1796 }
1797 Py_DECREF(retval);
1798 }
1799 else {
1800 ok = false;
1801 }
1802 BLI_assert(ok != -1);
1803 return bool(ok);
1804}
1805
1806bool PyC_RunString_AsStringOrNone(const char *imports[],
1807 const char *expr,
1808 const char *filename,
1809 char **r_value)
1810{
1811 size_t value_size;
1812 return PyC_RunString_AsStringAndSizeOrNone(imports, expr, filename, r_value, &value_size);
1813}
1814
1816
1817#endif /* #ifndef MATH_STANDALONE */
1818
1819/* -------------------------------------------------------------------- */
1823
1825{
1826 /* This is ported from CPython's internal #flush_std_files (2025-03-31). The code is a bit
1827 * different because the original code uses some internal APIs.
1828 *
1829 * This is approximately equivalent to:
1830 * \code{.py}
1831 * try:
1832 * sys.stdout.flush()
1833 * sys.stderr.flush()
1834 * except Exception:
1835 * pass
1836 * \endcode
1837 */
1838 PyObject *py_flush = PyUnicode_FromString("flush");
1839 BLI_assert(py_flush);
1840 for (const char *name : {"stdout", "stderr"}) {
1841 PyObject *py_file = PySys_GetObject(name);
1842 if (!py_file) {
1843 PyErr_Clear();
1844 continue;
1845 }
1846 PyObject *py_flush_retval = PyObject_CallMethodNoArgs(py_file, py_flush);
1847 if (py_flush_retval) {
1848 Py_DECREF(py_flush_retval);
1849 }
1850 else {
1851 PyErr_Clear();
1852 }
1853 }
1854 Py_DECREF(py_flush);
1855}
1856
1858
1859/* -------------------------------------------------------------------- */
1865
1866/* Compiler optimizes out redundant checks. */
1867#if defined(__GNUC__) && !defined(__clang__)
1868# pragma GCC diagnostic push
1869# pragma GCC diagnostic ignored "-Wtype-limits"
1870
1871#endif
1872
1873/* #PyLong_AsUnsignedLong, unlike #PyLong_AsLong, does not fall back to calling #PyNumber_Index
1874 * when its argument is not a `PyLongObject` instance. To match parsing signed integer types with
1875 * #PyLong_AsLong, this function performs the #PyNumber_Index fallback, if necessary, before
1876 * calling #PyLong_AsUnsignedLong. */
1877static ulong pyc_Long_AsUnsignedLong(PyObject *value)
1878{
1879 if (value == nullptr) {
1880 /* Let PyLong_AsUnsignedLong handle error raising. */
1881 return PyLong_AsUnsignedLong(value);
1882 }
1883
1884 if (PyLong_Check(value)) {
1885 return PyLong_AsUnsignedLong(value);
1886 }
1887
1888 /* Call `__index__` like PyLong_AsLong. */
1889 PyObject *value_converted = PyNumber_Index(value);
1890 if (value_converted == nullptr) {
1891 /* A `TypeError` will have been raised. */
1892 return ulong(-1);
1893 }
1894 ulong to_return = PyLong_AsUnsignedLong(value_converted);
1895 Py_DECREF(value_converted);
1896 return to_return;
1897}
1898
1899int PyC_Long_AsBool(PyObject *value)
1900{
1901 const int test = PyLong_AsInt(value);
1902 if (test == -1 && PyErr_Occurred()) [[unlikely]] {
1903 return -1;
1904 }
1905 if (uint(test) > 1) [[unlikely]] {
1906 PyErr_SetString(PyExc_TypeError, "Python number not a bool (0/1)");
1907 return -1;
1908 }
1909 return test;
1910}
1911
1912int8_t PyC_Long_AsI8(PyObject *value)
1913{
1914 const int test = PyLong_AsInt(value);
1915 if (test == -1 && PyErr_Occurred()) [[unlikely]] {
1916 return -1;
1917 }
1918 if (test < INT8_MIN || test > INT8_MAX) [[unlikely]] {
1919 PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int8");
1920 return -1;
1921 }
1922 return int8_t(test);
1923}
1924
1925int16_t PyC_Long_AsI16(PyObject *value)
1926{
1927 const int test = PyLong_AsInt(value);
1928 if (test == -1 && PyErr_Occurred()) [[unlikely]] {
1929 return -1;
1930 }
1931 if (test < INT16_MIN || test > INT16_MAX) [[unlikely]] {
1932 PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int16");
1933 return -1;
1934 }
1935 return int16_t(test);
1936}
1937
1938/* Inlined in header:
1939 * PyC_Long_AsI32
1940 * PyC_Long_AsI64
1941 */
1942
1943uint8_t PyC_Long_AsU8(PyObject *value)
1944{
1945 const ulong test = pyc_Long_AsUnsignedLong(value);
1946 if (test == ulong(-1) && PyErr_Occurred()) [[unlikely]] {
1947 return uint8_t(-1);
1948 }
1949 if (test > UINT8_MAX) [[unlikely]] {
1950 PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C uint8");
1951 return uint8_t(-1);
1952 }
1953 return uint8_t(test);
1954}
1955
1956uint16_t PyC_Long_AsU16(PyObject *value)
1957{
1958 const ulong test = pyc_Long_AsUnsignedLong(value);
1959 if (test == ulong(-1) && PyErr_Occurred()) [[unlikely]] {
1960 return uint16_t(-1);
1961 }
1962 if (test > UINT16_MAX) [[unlikely]] {
1963 PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C uint16");
1964 return uint16_t(-1);
1965 }
1966 return uint16_t(test);
1967}
1968
1969uint32_t PyC_Long_AsU32(PyObject *value)
1970{
1971 const ulong test = pyc_Long_AsUnsignedLong(value);
1972 if (test == ulong(-1) && PyErr_Occurred()) [[unlikely]] {
1973 return uint32_t(-1);
1974 }
1975 if (test > UINT32_MAX) [[unlikely]] {
1976 PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C uint32");
1977 return uint32_t(-1);
1978 }
1979 return uint32_t(test);
1980}
1981
1982uint64_t PyC_Long_AsU64(PyObject *value)
1983{
1984 if (value == nullptr) {
1985 /* Let PyLong_AsUnsignedLongLong handle error raising. */
1986 return uint64_t(PyLong_AsUnsignedLongLong(value));
1987 }
1988
1989 if (PyLong_Check(value)) {
1990 return uint64_t(PyLong_AsUnsignedLongLong(value));
1991 }
1992
1993 /* Call `__index__` like PyLong_AsLongLong. */
1994 PyObject *value_converted = PyNumber_Index(value);
1995 if (value_converted == nullptr) {
1996 /* A `TypeError` will have been raised. */
1997 return uint64_t(-1);
1998 }
1999
2000 uint64_t to_return = uint64_t(PyLong_AsUnsignedLongLong(value_converted));
2001 Py_DECREF(value_converted);
2002 return to_return;
2003}
2004
2005#if defined(__GNUC__) && !defined(__clang__)
2006# pragma GCC diagnostic pop
2007#endif
2008
2010
2011/* -------------------------------------------------------------------- */
2014
2015char PyC_StructFmt_type_from_str(const char *typestr)
2016{
2017 switch (typestr[0]) {
2018 case '!':
2019 case '<':
2020 case '=':
2021 case '>':
2022 case '@':
2023 return typestr[1];
2024 default:
2025 return typestr[0];
2026 }
2027}
2028
2030{
2031 switch (format) {
2032 case 'f':
2033 case 'd':
2034 case 'e':
2035 return true;
2036 default:
2037 return false;
2038 }
2039}
2040
2042{
2043 switch (format) {
2044 case 'i':
2045 case 'I':
2046 case 'l':
2047 case 'L':
2048 case 'h':
2049 case 'H':
2050 case 'b':
2051 case 'B':
2052 case 'q':
2053 case 'Q':
2054 case 'n':
2055 case 'N':
2056 case 'P':
2057 return true;
2058 default:
2059 return false;
2060 }
2061}
2062
2064{
2065 switch (format) {
2066 case 'c':
2067 case 's':
2068 case 'p':
2069 return true;
2070 default:
2071 return false;
2072 }
2073}
2074
2076{
2077 switch (format) {
2078 case '?':
2079 return true;
2080 default:
2081 return false;
2082 }
2083}
2084
2086
2087/* -------------------------------------------------------------------- */
2090
2092{
2093 PyObject *key;
2094 Py_ssize_t pos = 0;
2095 while (PyDict_Next(dict, &pos, &key, nullptr)) {
2096 if (!PyUnicode_Check(key)) {
2097 return false;
2098 }
2099 }
2100 return true;
2101}
2102
2104
2105/* -------------------------------------------------------------------- */
2116
2117#ifndef MATH_STANDALONE
2118
2135
2137{
2138 /* `info.buf` is asserted non-null at construction.
2139 * #MEM_delete_void also accepts null defensively. */
2140 MEM_delete_void(self->info.buf);
2141 Py_TYPE(self)->tp_free(self);
2142}
2143
2144static int bpy_memoryview_buffer_getbuffer(BPyMemoryViewOwned *self, Py_buffer *view, int flags)
2145{
2146 if (self->info.readonly && (flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) {
2147 PyErr_SetString(PyExc_BufferError, "BPyMemoryViewOwned: object is not writable");
2148 return -1;
2149 }
2150 *view = self->info;
2151 view->obj = Py_NewRef(reinterpret_cast<PyObject *>(self));
2152 /* Honor what the caller actually requested. */
2153 if ((flags & PyBUF_FORMAT) != PyBUF_FORMAT) {
2154 view->format = nullptr;
2155 }
2156 if ((flags & PyBUF_ND) != PyBUF_ND) {
2157 view->shape = nullptr;
2158 }
2159 if ((flags & PyBUF_STRIDES) != PyBUF_STRIDES) {
2160 view->strides = nullptr;
2161 }
2162 return 0;
2163}
2164
2165static PyBufferProcs bpy_memoryview_buffer_as_buffer = {
2166 /*bf_getbuffer*/ reinterpret_cast<getbufferproc>(bpy_memoryview_buffer_getbuffer),
2167 /*bf_releasebuffer*/ nullptr,
2168};
2169
2170static PyTypeObject BPyMemoryViewOwned_Type = {
2171 PyVarObject_HEAD_INIT(nullptr, 0)
2172 /*tp_name*/ "BPyMemoryViewOwned",
2173 /*tp_basicsize*/ sizeof(BPyMemoryViewOwned),
2174 /*tp_itemsize*/ sizeof(Py_ssize_t),
2175 /*tp_dealloc*/ reinterpret_cast<destructor>(bpy_memoryview_buffer_dealloc),
2176 /*tp_vectorcall_offset*/ 0,
2177 /*tp_getattr*/ nullptr,
2178 /*tp_setattr*/ nullptr,
2179 /*tp_as_async*/ nullptr,
2180 /*tp_repr*/ nullptr,
2181 /*tp_as_number*/ nullptr,
2182 /*tp_as_sequence*/ nullptr,
2183 /*tp_as_mapping*/ nullptr,
2184 /*tp_hash*/ nullptr,
2185 /*tp_call*/ nullptr,
2186 /*tp_str*/ nullptr,
2187 /*tp_getattro*/ nullptr,
2188 /*tp_setattro*/ nullptr,
2189 /*tp_as_buffer*/ &bpy_memoryview_buffer_as_buffer,
2190 /* `Py_TPFLAGS_HAVE_GC` (and the matching `tp_traverse` / `tp_clear`) is not
2191 * needed: the wrapper holds no Python references - `info.obj` /
2192 * `info.suboffsets` / `info.internal` are explicitly nulled at construction
2193 * and the buffer is plain memory. */
2194 /*tp_flags*/ Py_TPFLAGS_DEFAULT,
2195 /*tp_doc*/ nullptr,
2196};
2197
2198PyObject *PyC_MemoryView_FromBufferOwned(const Py_buffer *info)
2199{
2200 BLI_assert(info->buf != nullptr);
2201 BLI_assert(info->ndim >= 1);
2202 BLI_assert(info->itemsize > 0);
2203 BLI_assert(info->format != nullptr);
2204 BLI_assert(info->shape != nullptr);
2205 BLI_assert(info->strides != nullptr);
2206
2207 if (PyType_Ready(&BPyMemoryViewOwned_Type) < 0) [[unlikely]] {
2208 MEM_delete_void(info->buf);
2209 return nullptr;
2210 }
2211 BPyMemoryViewOwned *wrapper = PyObject_NewVar(
2212 BPyMemoryViewOwned, &BPyMemoryViewOwned_Type, Py_ssize_t(2) * info->ndim);
2213 if (wrapper == nullptr) [[unlikely]] {
2214 MEM_delete_void(info->buf);
2215 return nullptr;
2216 }
2217 wrapper->info = *info;
2218 wrapper->info.obj = nullptr;
2219 wrapper->info.shape = wrapper->shape_and_stride;
2220 wrapper->info.strides = wrapper->shape_and_stride + info->ndim;
2221 wrapper->info.suboffsets = nullptr;
2222 wrapper->info.internal = nullptr;
2223 const size_t dim_size = size_t(info->ndim) * sizeof(Py_ssize_t);
2224 memcpy(wrapper->shape_and_stride, info->shape, dim_size);
2225 memcpy(wrapper->shape_and_stride + info->ndim, info->strides, dim_size);
2226 /* `wrapper` now owns `info->buf`, its `tp_dealloc` will free it. */
2227
2228 PyObject *mv = PyMemoryView_FromObject(reinterpret_cast<PyObject *>(wrapper));
2229 Py_DECREF(wrapper);
2230 return mv;
2231}
2232
2233#endif /* !MATH_STANDALONE */
2234
2236
2237} // namespace blender
#define UINT16_MAX
#define INT8_MAX
#define UINT32_MAX
#define INT16_MAX
#define UINT8_MAX
#define ATTR_NONNULL(...)
Read Blender memory allocation and freeing.
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define ELEM(...)
#define POINTER_OFFSET(v, ofs)
#define STREQ(a, b)
#define str(s)
VecBase< float, D > constexpr mod(VecOp< float, D >, VecOp< float, D >) RET
float length(VecOp< float, D >) RET
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
std::string filename(const std::string_view &str, size_t pos)
BMesh Iterators.
PyObject * PyC_MainModule_Backup()
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
PyObject * PyC_Tuple_PackArray_String(const char **array, uint len)
int PyC_FlagSet_ToBitfield(const PyC_FlagSet *items, PyObject *value, int *r_value, const char *error_prefix)
size_t size_t size_t BLI_snprintf_utf8(char *__restrict dst, size_t dst_maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
int PyC_AsArray_FAST(void *array, const size_t array_item_size, PyObject *value_fast, const Py_ssize_t length, const PyTypeObject *type, const char *error_prefix)
unsigned __int64 uint64_t
Definition BKE_text.h:91
bool PyC_IsInterpreterActive()
int PyC_ParseOptionalDouble(PyObject *o, void *p)
static PyBufferProcs bpy_memoryview_buffer_as_buffer
__int64 int64_t
Definition BKE_text.h:90
bool PyC_RunString_AsNumber(const char *imports[], const char *expr, const char *filename, double *r_value)
PyObject * PyC_FrozenSetFromStrings(const char **strings)
PyObject * PyC_Err_SetString_Prefix(PyObject *exception_type_prefix, const char *str)
int PyC_ParseOptionalUInt(PyObject *o, void *p)
static void pyc_exception_buffer_handle_system_exit()
int PyC_ParseBool(PyObject *o, void *p)
unsigned int uint
Definition BKE_text.h:55
PyObject * PyC_MemoryView_FromBufferOwned(const Py_buffer *info)
int PyC_CheckArgs_DeepCopy(PyObject *args)
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
static PyObject * PyC_Tuple_PackArray_Multi_Bool_impl(const bool **array_p, const int dims[], const int dims_len)
char PyC_StructFmt_type_from_str(const char *typestr)
PyObject * PyC_Tuple_PackArray_Multi_F64(const double *array, const int dims[], const int dims_len)
unsigned long ulong
Definition BKE_text.h:57
char * BLI_strncpy_utf8(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
int PyC_AsArray(void *array, const size_t array_item_size, PyObject *value, const Py_ssize_t length, const PyTypeObject *type, const char *error_prefix)
PyObject * PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag)
static int bpy_memoryview_buffer_getbuffer(BPyMemoryViewOwned *self, Py_buffer *view, int flags)
int PyC_FlagSet_ValueFromID(const PyC_FlagSet *item, const char *identifier, int *r_value, const char *error_prefix)
static PyTypeObject BPyMemoryViewOwned_Type
int PyC_ParseRectI(PyObject *o, void *p)
static int PyC_AsArray_Multi_impl(void **array_p, const size_t array_item_size, PyObject *value, const int *dims, const int dims_len, const PyTypeObject *type, const char *error_prefix)
void PyC_FileAndNum_Safe(const char **r_filename, int *r_lineno)
void MEM_delete_void(void *vmemh)
PyObject * PyC_UnicodeFromBytes(const char *str)
void PyC_LineSpit()
int PyC_FlagSet_ValueFromID_int(const PyC_FlagSet *item, const char *identifier, int *r_value)
static int PyC_AsArray_Multi_FAST_impl(void **array_p, const size_t array_item_size, PyObject *value_fast, const int *dims, const int dims_len, const PyTypeObject *type, const char *error_prefix)
unsigned short uint16_t
Definition BKE_text.h:80
PyObject * PyC_Tuple_PackArray_Multi_Bool(const bool *array, const int dims[], const int dims_len)
unsigned int uint32_t
Definition BKE_text.h:81
bool PyC_Dict_CheckKeysAreStrings(PyObject *dict)
PyObject * PyC_DefaultNameSpace(const char *filename)
PyObject * PyC_Tuple_PackArray_I32FromBool(const int *array, uint len)
static void bpy_memoryview_buffer_dealloc(BPyMemoryViewOwned *self)
BMesh const char void * data
bool PyC_RunString_AsStringAndSizeOrNone(const char *imports[], const char *expr, const char *filename, char **r_value, size_t *r_value_size)
static ulong pyc_Long_AsUnsignedLong(PyObject *value)
void PyC_ObSpit(const char *name, PyObject *var)
unsigned char uint8_t
Definition BKE_text.h:79
int16_t PyC_Long_AsI16(PyObject *value)
std::optional< int > PyC_ExceptionSystemExitCode()
PyObject * PyC_Tuple_PackArray_Multi_F32(const float *array, const int dims[], const int dims_len)
static PyObject * PyC_Tuple_PackArray_Multi_I32_impl(const int **array_p, const int dims[], const int dims_len)
int PyC_ParseOptionalInt(PyObject *o, void *p)
PyObject * PyC_ExceptionBuffer_Simple()
int PyC_ParseUnicodeAsBytesAndSize(PyObject *o, void *p)
void PyC_List_Fill(PyObject *list, PyObject *value)
PyObject * PyC_Tuple_PackArray_I32(const int *array, uint len)
uint64_t PyC_Long_AsU64(PyObject *value)
PyObject * PyC_FlagSet_AsString(const PyC_FlagSet *item)
void PyC_RunQuicky(const char *filepath, int n,...)
const char * PyC_StringEnum_FindIDFromValue(const PyC_StringEnumItems *items, const int value)
bool PyC_RunString_AsStringAndSize(const char *imports[], const char *expr, const char *filename, char **r_value, size_t *r_value_size)
uint8_t PyC_Long_AsU8(PyObject *value)
bool PyC_RunString_AsIntPtr(const char *imports[], const char *expr, const char *filename, intptr_t *r_value)
PyObject * PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format,...)
const char * PyC_UnicodeAsBytes(PyObject *py_str, PyObject **r_coerce)
void PyC_Err_PrintWithFunc(PyObject *py_func)
bool PyC_RunString_AsStringOrNone(const char *imports[], const char *expr, const char *filename, char **r_value)
static PyObject * PyC_Tuple_PackArray_Multi_F32_impl(const float **array_p, const int dims[], const int dims_len)
static std::optional< int > g_system_exit_code
int PyC_Long_AsBool(PyObject *value)
int PyC_AsArray_Multi_FAST(void *array, const size_t array_item_size, PyObject *value_fast, const int *dims, const int dims_len, const PyTypeObject *type, const char *error_prefix)
uint32_t PyC_Long_AsU32(PyObject *value)
void * PyC_RNA_AsPointer(PyObject *value, const char *type_name)
void PyC_Tuple_Fill(PyObject *tuple, PyObject *value)
PyObject * PyC_Tuple_PackArray_Multi_I32(const int *array, const int dims[], const int dims_len)
uint16_t PyC_Long_AsU16(PyObject *value)
bool PyC_StructFmt_type_is_bool(char format)
void PyC_StdFilesFlush()
bool PyC_StructFmt_type_is_float_any(char format)
PyObject * PyC_Tuple_PackArray_F64(const double *array, uint len)
void PyC_FileAndNum(const char **r_filename, int *r_lineno)
PyObject * PyC_Tuple_PackArray_F32(const float *array, uint len)
int PyC_ParseOptionalRectI(PyObject *o, void *p)
int PyC_Module_AddToSysModules(PyObject *sys_modules, PyObject *module)
void PyC_MainModule_Restore(PyObject *main_mod)
signed int int32_t
Definition BKE_text.h:78
static PyObject * PyC_Tuple_PackArray_Multi_F64_impl(const double **array_p, const int dims[], const int dims_len)
void PyC_StackSpit()
PyObject * PyC_UnicodeFromStdStr(const std::string &str)
PyObject * PyC_ExceptionBuffer()
bool PyC_RunString_AsString(const char *imports[], const char *expr, const char *filename, char **r_value)
int PyC_ParseStringEnum(PyObject *o, void *p)
bool PyC_NameSpace_ImportArray(PyObject *py_dict, const char *imports[])
PyObject * PyC_UnicodeFromBytesAndSize(const char *str, Py_ssize_t size)
bool PyC_StructFmt_type_is_int_any(char format)
void PyC_ObSpitStr(char *result, size_t result_maxncpy, PyObject *var)
bool PyC_Err_CaptureSystemExitCode()
int8_t PyC_Long_AsI8(PyObject *value)
int PyC_ParseUnicodeAsBytesAndSize_OrNone(PyObject *o, void *p)
static PyObject * pyc_run_string_as_py_object(const char *imports[], const char *imports_star[], const char *expr, const char *filename) ATTR_NONNULL(3
int PyC_ParseTypeOrNone(PyObject *o, void *p)
PyObject * PyC_Tuple_PackArray_Bool(const bool *array, uint len)
int PyC_AsArray_Multi(void *array, const size_t array_item_size, PyObject *value, const int *dims, const int dims_len, const PyTypeObject *type, const char *error_prefix)
int PyC_ParseOptionalBool(PyObject *o, void *p)
int PyC_ParseOptionalFloat(PyObject *o, void *p)
ATTR_WARN_UNUSED_RESULT const BMVert const BMEdge * e
signed char int8_t
Definition BKE_text.h:76
bool PyC_StructFmt_type_is_byte(char format)
signed short int16_t
Definition BKE_text.h:77
_W64 int intptr_t
Definition BKE_text.h:119
const char * PyC_UnicodeAsBytesAndSize(PyObject *py_str, Py_ssize_t *r_size, PyObject **r_coerce)
header-only utilities
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float