gpt4 book ai didi

c - 如何存储来自 sqlite3_open 的数据库连接句柄?

转载 作者:行者123 更新时间:2023-12-03 17:02:10 25 4
gpt4 key购买 nike

为了使用 ISO_C_BINDING 模块从 Fortran 2003 程序调用它们。我在 Windows 上使用 Intel Fortran 17 编译器 (ifort) 和 MSVC 14,在 Linux 上使用 gcc。

我的目标是打开 SQLite 数据库并存储指向数据库连接句柄的指针,以便在 Fortran 程序循环计算时使用它来存储/检索结果。主程序伪代码看起来像这样:

program main
use, intrinsic :: iso_c_binding
use sqlite_wrapper_module
implicit none

! QUESTION: SHOULD DB_HANDLE BE TYPE(C_PTR) OR A STRUCT OF SOME KIND?
type(C_PTR) :: db_handle

character(len=:), allocatable :: db_name

db_name = "test.db"//C_NULL_CHAR
call sqlite3_open_WRAPPER(db_name, db_handle) ! wraps sqlite3_open

do i=1,n
...compute stuff...
call sqlite3_exec_WRAPPER(db_handle, sql_stmt) ! wraps sqlite3_exec
...compute stuff...
enddo

call sqlite3_close_WRAPPER(db_handle) ! wraps sqlite3_close
end program main

我已经在单独的模块中定义了包装器 C 例程的显式接口(interface)。例如:

module sqlite_wrapper_module
use, intrisic :: iso_c_binding
implicit none
interface
subroutine sqlite3_open_WRAPPER(db_name, db_handle) bind(C)
import
character(kind=C_CHAR), dimension(*) :: db_name
type(C_PTR), value :: db_handle
end subroutine sqlite3_open_wrapper
end interface
end module sqlite_wrapper_module

我不确定我是否理解 official docs , 但他们似乎声明 *db 是一个代表数据库连接句柄的指针,它是一个定义为 typedef struct sqlite3 sqlite3; 的“不透明结构”。我不知道那到底是什么意思(C 编程不是我的强项)。所以我尝试从 Fortran 中设置 C_PTR,如下所示:

int sqlite3_open_WRAPPER(char *filename, sqlite3 *pdb) {
sqlite3 *db;
int rc=sqlite3_open(filename, &db);
pdb=db; // <---------------------------------This
...check rc...
return 0;
}

起初,这似乎行得通。但是,该指针一旦传回 Fortran 程序就返回 NULL,并且不能在 sqlite3_execsqlite3_close 中使用。我是否应该在 Fortran 程序中定义某种 struct 来充当数据库连接结构,并将其传递到 C 例程中?

最佳答案

您正在将一个值 (db) 赋给一个局部变量 (pdb),该变量的生命周期以该函数结束,使用指向指针的指针以使那些在函数外可见的变化:

int sqlite3_open_WRAPPER(char *filename, sqlite3 *pdb) {
sqlite3 *db;
int rc=sqlite3_open(filename, &db);
pdb=db; // <---------------------------------This
...check rc...
return 0;
}

应该是

int sqlite3_open_WRAPPER(char *filename, sqlite3 **pdb) {
sqlite3 *db;
int rc=sqlite3_open(filename, &db);
*pdb=db; // <---------------------------------This
...check rc...
return 0;
}

或者更好的是,直接使用pdb:

int sqlite3_open_WRAPPER(char *filename, sqlite3 **pdb) {
int rc=sqlite3_open(filename, pdb);
...check rc...
return 0;
}

关于c - 如何存储来自 sqlite3_open 的数据库连接句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42271256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com