I want to convert the source to a smart pointer. But I found one I don’t understand why it can’t. How can this be solved with the code below?
Old code style:
bool PyTuple_GetTextInstance(PyObject* poArgs, int pos, CGraphicTextInstance** ppTextInstance)
{
int handle;
if (!PyTuple_GetInteger(poArgs, pos, &handle))
return false;
if (!handle)
return false;
*ppTextInstance=(CGraphicTextInstance*)handle;
return true;
}
new code style:
bool PyTuple_GetTextInstance(PyObject* poArgs, int pos, std::shared_ptr<CGraphicTextInstance>& ppTextInstance)
{
int handle;
if (!PyTuple_GetInteger(poArgs, pos, &handle))
return false;
if (!handle)
return false;
ppTextInstance=std::static_pointer_cast<CGraphicTextInstance>(handle);
return true;
}
why not work? problem: std::static_pointer_cast error
invitation:
PyObject* grpTextGetSize(PyObject* poSelf, PyObject* poArgs)
{
CGraphicTextInstance* pTextInstance;
if (!PyTuple_GetTextInstance(poArgs, 0, &pTextInstance))
return Py_BuildException();
int width, height;
pTextInstance->GetTextSize(&width, &height);
return Py_BuildValue("(i, i)", width, height);
}
PyTuple_GetInteger function:
bool PyTuple_GetInteger(PyObject* poArgs, int pos, int* ret)
{
if (pos >= PyTuple_Size(poArgs))
return false;
PyObject* poItem = PyTuple_GetItem(poArgs, pos);
if (!poItem)
return false;
*ret = PyLong_AsLong(poItem);
return true;
}
Assuming that the original code is correct and that handle
is really a pointer to a CGraphicTextInstance
under the skin, then you need to replace this:
ppTextInstance=std::static_pointer_cast<CGraphicTextInstance>(handle);
with this:
ppTextInstance = std::shared_ptr <CGraphicTextInstance>
(reinterpret_cast <CGraphicTextInstance *> (handle));
But it would be cleaner for this function to return a shared_ptr <CGraphicTextInstance>
, with the wrapped pointer set to nullptr
on failure.