如何使用libpq获取双精度浮点数值?

3

在libpq文档中的示例展示了如何通过将整数值转换为主机字节顺序来获取整数值。

我很好奇如何使用libpq(不使用libpqtyppes)获取双精度值?我已经尝试过reinterpret_cast,但没有成功。

此外,为什么文本和字节数据不需要进行字节顺序转换呢?

数据库在Windows 7上本地运行,我正在使用Visual C++ 2013。

pptr是我正在尝试检索的双精度值。

#include <iostream>
#include <memory>
#include <vector>
#include <libpq-fe.h>
#include <Winsock2.h>


static void
show_binary_results(PGresult *res)
{
    int i, j;
    int i_fnum, n_fnum, p_fnum;

    /* Use PQfnumber to avoid assumptions about field order in result */
    i_fnum = PQfnumber(res, "id");
    n_fnum = PQfnumber(res, "name");
    p_fnum = PQfnumber(res, "price");

    for (i = 0; i < PQntuples(res); i++)
    {
        char* iptr;
        char* nptr;
        char* pptr;
        int         blen;
        int         ival;

        /* Get the field values (we ignore possibility they are null!) */
        iptr = PQgetvalue(res, i, i_fnum);
        nptr = PQgetvalue(res, i, n_fnum);
        pptr = PQgetvalue(res, i, p_fnum); /*THIS IS A VALUE I AM TRYING TO GET*/

        /*
        * The binary representation of INT4 is in network byte order, which
        * we'd better coerce to the local byte order.
        */
        ival = ntohl(*((uint32_t *) iptr));

        /*
        * The binary representation of TEXT is, well, text, and since libpq
        * was nice enough to append a zero byte to it, it'll work just fine
        * as a C string.
        *
        * The binary representation of BYTEA is a bunch of bytes, which could
        * include embedded nulls so we have to pay attention to field length.
        */
        //blen = PQgetlength(res, i, b_fnum);

        printf("tuple %d: got\n", i);
        printf(" i = (%d bytes) %d\n",
            PQgetlength(res, i, i_fnum), ival);
        printf(" t = (%d bytes) '%s'\n",
            PQgetlength(res, i, n_fnum), nptr);
        printf(" p = (%d bytes) %f\n",
            PQgetlength(res, i, p_fnum), *reinterpret_cast<double*>(pptr));

        printf("\n\n");
    }
}


int main(int argc, char* argv [])
{
    auto conn_string = "postgresql://postgres:pwd@localhost/db";
    auto conn_deleter = [](PGconn* c) { PQfinish(c); };
    auto res_deleter = [](PGresult* r) { PQclear(r); std::cout << "deleted" << std::endl; };
    std::unique_ptr<PGconn, decltype(conn_deleter)> conn(PQconnectdb(conn_string), conn_deleter);

    if (PQstatus(conn.get()) != ConnStatusType::CONNECTION_OK)
        std::cerr << "Problem" << std::endl;

    std::vector<const char *> params{ "1" };
    std::unique_ptr < PGresult, decltype(res_deleter)> res(PQexecParams(conn.get(),
        "SELECT * FROM table_with_double WHERE id = $1",
        params.size(),       /* one param */
        NULL,    /* let the backend deduce param type */
        (const char * const *)&params.front(),
        NULL,    /* don't need param lengths since text */
        NULL,    /* default to all text params */
        1), /* ask for binary results */
        res_deleter);      

    if (PQresultStatus(res.get()) != ExecStatusType::PGRES_TUPLES_OK)
        std::cout << "SELECT failed: " << PQerrorMessage(conn.get()) << std::endl;
    show_binary_results(res.get());
}

你如何调用 PQgetvalue 函数? - Stephane Rolland
据我所知,在这个层次上,textbytea 基本上是美化过的 char*,因此无需担心字节序问题,同样,IEEE double 的位布局也是与机器无关的,因此在那里也不需要考虑字节序。 - mu is too short
@muistooshort,这是我所期望的,但我得到的双精度值为0。 - Kimi
@StephaneRolland,我已经发布了代码。 - Kimi
这里你要使用atof尝试转换结果值,这不是一个转换!你可以发布与你的问题相关的代码吗?即包含你尝试使用reinterpret_cast转换为float的代码? - Stephane Rolland
显示剩余5条评论
1个回答

4
显然,双列数据以大端方式传输,需要转换为小端。与整数相同。基于这篇文章和这个答案,我使用了一个简单的函数来交换双精度浮点值。
double double_swap(double d)
{
    union
    {
        double d;
        unsigned char bytes[8];
    } src, dest;

    src.d = d;
    dest.bytes[0] = src.bytes[7];
    dest.bytes[1] = src.bytes[6];
    dest.bytes[2] = src.bytes[5];
    dest.bytes[3] = src.bytes[4];
    dest.bytes[4] = src.bytes[3];
    dest.bytes[5] = src.bytes[2];
    dest.bytes[6] = src.bytes[1];
    dest.bytes[7] = src.bytes[0];
    return dest.d;
}

应用这个函数可以从数据库中检索到正确的值。
printf(" p = (%d bytes) %lf\n",
            PQgetlength(res, i, p_fnum), double_swap(*((double*) pptr)));

请考虑使用std::cout <<而不是printf。这被认为是C++而不是C。它还可以在运行时执行所有常见的转换。 - Stephane Rolland
@StephaneRolland,这是来自libpq示例的代码,我这样做是为了表明我没有做任何不寻常的事情。我同意这段代码不应该通过任何代码审查。 - Kimi
由于OP明确提到了MS Windows(尽管不是8),因此可以使用htonll来交换64位长整型/盲目转换的双精度浮点数的字节顺序。 - mlt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接