Messy, but monumental: PyTexture::pyObject works

this also coincidentally fixes a weird bug I encountered while
(mis?)using tp_alloc: by using PyType_GenericAlloc, I avoid the segfault
that tp_alloc sometimes causes. See the horrible UIDrawable retrieval
macro that I use in UI.h for a workaround that can probably be replaced
with this technique
This commit is contained in:
John McCardle 2024-03-21 21:39:15 -04:00
commit d7228172c4
5 changed files with 110 additions and 51 deletions

View file

@ -1,4 +1,6 @@
#include "PyTexture.h"
using namespace mcrfpydef;
PyTexture::PyTexture(std::string filename, int sprite_w, int sprite_h)
: source(filename), sprite_width(sprite_w), sprite_height(sprite_h)
@ -15,6 +17,17 @@ PyTexture::PyTexture(std::string filename, int sprite_w, int sprite_h)
}
}
/* // bit misguided here: holding self might prevent the shared_ptr from ever being released.
PyTexture::~PyTexture()
{
if (self != NULL)
{
(PyTextureObject*)self->data.reset();
Py_DECREF(self);
}
}
*/
sf::Sprite PyTexture::sprite(int index, sf::Vector2f pos, sf::Vector2f s)
{
int tx = index % sheet_width, ty = index / sheet_width;
@ -25,6 +38,28 @@ sf::Sprite PyTexture::sprite(int index, sf::Vector2f pos, sf::Vector2f s)
return sprite;
}
PyObject* PyTexture::pyObject()
{
//PyTextureObject* self = (PyTextureObject*)pynew(&mcrfpydef::PyTextureType, NULL, NULL);
std::cout << "tp_alloc (GenericAlloc)" << std::endl;
//PyObject* obj = ((&PyTextureType)->tp_alloc(&PyTextureType, 0));
//PyObject* obj = pynew(&PyTextureType);
PyObject* obj = PyType_GenericAlloc(&PyTextureType, 0);
std::cout << "alloc worked" << std::endl;
//Py_INCREF(self);
try {
std::cout << "assign data to self" << std::endl;
((PyTextureObject*)obj)->data = shared_from_this();
}
catch (std::bad_weak_ptr& e)
{
std::cout << "Bad weak ptr: shared_from_this() failed" << std::endl;
}
// TODO - shared_from_this will raise an exception if the object does not have a shared pointer. Constructor should be made private; write a factory function
std::cout << "returning PyObject" << std::endl;
return obj;
}
Py_hash_t PyTexture::hash(PyObject* obj)
{
auto self = (PyTextureObject*)obj;