c++ - sqlite3 将数据转换为短数组

标签 c++ c sqlite type-conversion

我在带有 Modbus 的嵌入式系统上使用 sqlite3。我需要将 sqlite3 的 select 语句结果中的信息打包到一个 Shorts 数组中,以便能够通过 Modbus 传递。

目前,我只使用 sqlite3 中的 2 种数据类型(TEXT 和 INT)。我正在尝试将每列结果打包到一个短裤数组中。例如:

typedef struct
{
    short unitSN[4];
    short unitClass[1];
}UnitSettings;

UnitSettings unitSettings;

// prepare and execute select statement for table, then put into structs members
s = sqlite3_prepare(db, sqlstmt, strlen(sqlstmt), &stmt, &pzTest);
s = sqlite3_step( stmt );

// I want to do something like this:
unitSettings.unitSN[] = sqlite3_column_text(stmt, 0);
unitSettings.unitClass[] = sqlite3_column_int(stmt, 1);

我正在考虑创建函数来从 unsigned char* (sqlite3_column_text 的结果)转换为短数组,以及将 int 转换为短数组。这是解决问题的方法吗?或者是否有适当的方法来即时转换这些结果?

此外,正在考虑使结构与 sqlite3 表类型匹配以便于复制,然后在最后有一个函数来运行每个结构成员并将其转换为一个 Shorts 数组。

编辑:我刚刚读到了结构内的 union ,我认为这正是我所需要的:

typedef struct
{
    union
    {
        unsigned char* unitSN;
        short unitSNArr[4]; 
    }

    union
    {
        int unitClass;
        short unitClassArr[1];
    }  
}UnitSettings;

它说现在他们都查看同一 block 内存,但可以以不同的方式读取它,这就是我想要的。这比任何类型的转换都容易得多,对吗?

最佳答案

sqlite 不会自动为您提供这些转换。您必须自己进行转换。

我只会使用纯文本访问,然后编写自由函数将访问转换为短文本。像这样的东西,不太确定什么接口(interface)对您的访问最有意义。

void read_short(const char* data, size_t index, short& val) {
  val = *(reintepret_cast<short*>(&data[index*2]));
}

也许您的用例已经将它们放在短裤数组或其他东西中?如果这实际上是您使用数据的方式,我可能仍然只会在每个字段上做一个简短的操作。

就我个人而言,如果您可以帮助的话,我会将它们作为整数放入数据库中。您必须编写特殊的工具才能查看数据库值,这对于维护来说不太友好。

关于c++ - sqlite3 将数据转换为短数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174174/

相关文章:

c++ - 虚幻引擎 4 : Converting DrawMesh() from Unity

c++ - 成员函数和复制构造函数

c - 使用c中的dll在Labview中处理图像

c - 关于关于强制转换的编译器警告

SQLite - 按兰德排序()

SQLite - 如果存在则更新(而不是替换),否则插入

c++ - 什么是段错误?

C++17 标准库包括不在 Visual Studio 2017 中使用 Android 项目

c++ - C和C++中将int值转换为char指针的区别

python - 在 Colab 中升级 SQLite