(CLASS*)int 到 shared_ptr<CLASS>(int) 无效

(CLASS*)int to shared_ptr<CLASS>(int) not work

我想将源代码转换为智能指针。 但是我发现了一个我不明白为什么它不能。 如何用下面的代码解决这个问题?

旧代码风格:

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;
}

新的代码风格:

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;
}

为什么不工作?问题:std::static_pointer_cast 错误

邀请:

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函数:

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;
}

假设原来的代码是正确的,并且handle确实是一个指向皮肤下的CGraphicTextInstance的指针,那么你需要替换这个:

ppTextInstance=std::static_pointer_cast<CGraphicTextInstance>(handle);

有了这个:

ppTextInstance = std::shared_ptr <CGraphicTextInstance>
    (reinterpret_cast <CGraphicTextInstance *> (handle));

但是这个函数 return a shared_ptr <CGraphicTextInstance> 会更清晰,失败时包装指针设置为 nullptr