c ++ sqllite3读取blob不起作用

时间:2013-11-13 16:45:52

标签: c++ sqlite

有人可以指导我吗,

我似乎无法正确阅读我的blob。

我不知道什么是错的,有人可以帮忙吗?

这是我的功能:

我要做的是:

将bob作为二进制读取并将字节存储在char * data;

有人可以帮忙吗?

    int baramdb::dbreadblob(int pid)
{
    sqlite3_stmt *res;

    const char *tail;
    int count = 0;
    this->dbopen(this->dbfile); 

    if (sqlite3_prepare_v2(this->db, "SELECT * FROM Packet_Send_Queue", 128, &res, &tail) != SQLITE_OK)
    {
        printf("[Baram] Can't retrieve data: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return(1);
    }

    while (sqlite3_step(res) == SQLITE_ROW)
    {

        int *plength = 0;       
        *plength = sqlite3_column_bytes(res, 2);

        unsigned char **pbuffer = (unsigned char **)malloc(*plength);

        memcpy(*pbuffer, sqlite3_column_blob(res, 0), *plength);
        count++;
    }

    sqlite3_close(this->db);        
    this->lastresult = count;

    return count;
}

1 个答案:

答案 0 :(得分:2)

似乎你不明白“指针”是什么以及如何使用它。

然后,sqlite3_column_bytes返回int而不是int*

int length = sqlite3_column_bytes(res, 2);

在当前情况下这绝对不正确:

unsigned char **pbuffer = (unsigned char **)malloc(*plength);

如果您正在使用C ++ - 尝试不显式使用malloc / new,请改用智能指针或STL容器:

std::vector<char> data( length );

const char *pBuffer = reinterpret_cast<const char*>( sqlite3_column_blob(res, 2) );
std::copy( pBuffer, pBuffer + data.size(), &data[0] );

就是这样。