cffi.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #pragma once
  2. #include "common.h"
  3. #include "vm.h"
  4. namespace pkpy {
  5. #define PY_CLASS(T, mod, name) \
  6. static Type _type(VM* vm) { \
  7. static const StrName __x0(#mod); \
  8. static const StrName __x1(#name); \
  9. return OBJ_GET(Type, vm->_modules[__x0]->attr(__x1)); \
  10. } \
  11. static void _check_type(VM* vm, PyObject* val){ \
  12. if(!vm->isinstance(val, T::_type(vm))){ \
  13. vm->TypeError("expected '" #mod "." #name "', got " + OBJ_NAME(val).escape()); \
  14. } \
  15. } \
  16. static PyObject* register_class(VM* vm, PyObject* mod) { \
  17. if(OBJ_NAME(mod) != #mod) { \
  18. auto msg = fmt("register_class() failed: ", OBJ_NAME(mod), " != ", #mod); \
  19. throw std::runtime_error(msg); \
  20. } \
  21. PyObject* type = vm->new_type_object(mod, #name, vm->tp_object); \
  22. T::_register(vm, mod, type); \
  23. type->attr()._try_perfect_rehash(); \
  24. return type; \
  25. }
  26. #define VAR_T(T, ...) vm->heap.gcnew<T>(T::_type(vm), T(__VA_ARGS__))
  27. struct VoidP{
  28. PY_CLASS(VoidP, c, void_p)
  29. void* ptr;
  30. VoidP(void* ptr): ptr(ptr){}
  31. VoidP(): ptr(nullptr){}
  32. static void _register(VM* vm, PyObject* mod, PyObject* type){
  33. vm->bind_default_constructor<VoidP>(type);
  34. vm->bind_method<0>(type, "__repr__", [](VM* vm, ArgsView args){
  35. VoidP& self = _CAST(VoidP&, args[0]);
  36. std::stringstream ss;
  37. ss << "<void* at " << self.ptr << ">";
  38. return VAR(ss.str());
  39. });
  40. }
  41. };
  42. inline void add_module_c(VM* vm){
  43. PyObject* mod = vm->new_module("c");
  44. VoidP::register_class(vm, mod);
  45. }
  46. inline PyObject* py_var(VM* vm, void* p){
  47. return VAR_T(VoidP, p);
  48. }
  49. inline PyObject* py_var(VM* vm, char* p){
  50. return VAR_T(VoidP, p);
  51. }
  52. /***********************************************/
  53. template<typename T>
  54. T to_void_p(VM* vm, PyObject* var){
  55. static_assert(std::is_pointer_v<T>);
  56. VoidP& p = CAST(VoidP&, var);
  57. return reinterpret_cast<T>(p.ptr);
  58. }
  59. } // namespace pkpy