pod.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #pragma once
  2. #define PY_SSIZE_T_CLEAN
  3. #include <Python.h>
  4. #include "attr.h"
  5. #include "typedesc.h"
  6. namespace NPyBind {
  7. struct TPOD {
  8. TPyObjectPtr Dict;
  9. TPOD()
  10. : Dict(PyDict_New(), true)
  11. {
  12. }
  13. bool SetAttr(const char* name, PyObject* value) {
  14. return PyDict_SetItemString(Dict.Get(), name, value) == 0;
  15. }
  16. PyObject* GetAttr(const char* name) const {
  17. PyObject* res = PyDict_GetItemString(Dict.Get(), name);
  18. Py_XINCREF(res);
  19. return res;
  20. }
  21. };
  22. class TPODTraits: public NPyBind::TPythonType<TPOD, TPOD, TPODTraits> {
  23. private:
  24. typedef TPythonType<TPOD, TPOD, TPODTraits> MyParent;
  25. friend class TPythonType<TPOD, TPOD, TPODTraits>;
  26. TPODTraits();
  27. public:
  28. static TPOD* GetObject(TPOD& obj) {
  29. return &obj;
  30. }
  31. };
  32. template <>
  33. inline bool FromPyObject<TPOD*>(PyObject* obj, TPOD*& res) {
  34. res = TPODTraits::CastToObject(obj);
  35. if (res == nullptr)
  36. return false;
  37. return true;
  38. }
  39. template <>
  40. inline bool FromPyObject<const TPOD*>(PyObject* obj, const TPOD*& res) {
  41. res = TPODTraits::CastToObject(obj);
  42. if (res == nullptr)
  43. return false;
  44. return true;
  45. }
  46. }