我正在尝试在 C# 中导入 SQLite3 C 函数,但我不确定是否已正确导入它,即函数参数数据类型是否正确以及函数是否正确使用?该函数用于将图像数据(.png)插入到 Sqlite3 表中。
这是来自 SQLite website 的实际 C 实现:
int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
这是我在 C# 中的导入:
[DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob")]
private static extern int sqlite3_bind_blob (IntPtr stmHandle, int iIndex, string iParam, int iBytes, int iOperation);
在 C# 中使用 SQLite3 函数(注意该函数返回 21 - SQLITE_MISMATCH 20/* 数据类型不匹配 */
):
// blob is a byte[]
string query = "INSERT OR REPLACE INTO myTable(lat, lon, image) VALUES({1}, {2}, ?1)";
sqlite3_prepare_v2 (_connection, query, query.Length, out stmHandle, IntPtr.Zero)
int res = sqlite3_bind_blob (stmHandle, 1, blob.ToString(), blob.Length, SQLITE_TRANSIENT);
问题:
- 我是否使用正确的参数数据类型正确导入了 sqlite3_bind_blob DLL 函数?
- 我是否正确使用该函数,即我是否应该将 blob 转换为字符串,以及我是否正确获取 blob 的(字节数组)长度?
最佳答案
[DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob", CallingConvention = CallingConvention.Cdecl)]
private static extern int sqlite3_bind_blob (IntPtr stmHandle, int iIndex, byte[] iParam, int iBytes, IntPtr iOperation);
会是一个更好的签名。主要是因为System.String
是对内部结构未指定的类的引用,它甚至不等于wchar_t**
。
通过更正的导入,调用将如下所示
int res = sqlite3_bind_blob (stmHandle, 1, blob, blob.Length, SQLITE_TRANSIENT);
事实上,这正是 SQLite .NET 包装器所做的事情。
关于c# - 我是否可以将 SQLite3 C 函数正确导入到 C# 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20182160/