3

当我在 c++ 中使用函数来初始化 sqlite3 时,当它从函数中出来时,句柄为 Null。知道是什么原因造成的吗?我只是将指针作为参数传递。如果我将打开移动到主要功能,它工作正常。会发生什么导致这种情况?是否有隐藏的东西超出范围?

#include <iostream>
#include "sqlite3.h"

using namespace std;

int init_table(sqlite3 *dbH,  string db_name)
{
  if (sqlite3_open(db_name.c_str(), &dbH) != SQLITE_OK)
    {
      cout << "Failed to open DB : " << sqlite3_errmsg(dbH) << endl;
      abort();
    }
  else
    {
      cout << "Opened database: " << db_name << endl;
    }

  if (sqlite3_exec(dbH, "PRAGMA synchronous = OFF", NULL, NULL, NULL) != SQLITE_OK)
    {
      cout << "Failed to set synchronous: " << sqlite3_errmsg(dbH) << endl;
    }

  if (sqlite3_exec(dbH, "PRAGMA journal_mode = WAL", NULL, NULL, NULL) != SQLITE_OK)
    {
      cout << "Failed to set journal mode: " << sqlite3_errmsg(dbH) << endl;
    }

  cout << "dbH 2: " << dbH << endl;

}

int main()
{
  sqlite3 * dbH;
  dbH = NULL;
  cout << "dbH 1: " << dbH << endl;
  string dbName = "foo1.db";
  init_table(dbH, dbName);

  cout << "dbH 3: " << dbH << endl;
}

当运行

$ ./a.out
dbH 1: 0
Opened database: foo1.db
dbH 2: 0x5baa048
dbH 3: 0
4

1 回答 1

3

应该是

int init_table(sqlite3 **dbH,  string db_name)  

并将指针传递给指针?
可能是 sqliter 处理没有问题。您可以将指针作为引用传递,也可以作为指向指针的指针传递。

当然,在传递的时候,你需要传递&dbHinit_table修改后。

于 2013-08-28T13:33:13.847 回答