Am I Importing a SQLite3 C Function Correctly into C#

≡放荡痞女 提交于 2019-12-13 05:11:05

问题


I am attempting to import a SQLite3 C function inside C# but I am unsure I have imported it correctly, ie, that the function parameter data types are correct and that the function is being used correctly? The function is being used to insert a images data(.png) into a Sqlite3 table.

This is the actual C implementation from the SQLite website:

int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));

This is my import in C#:

[DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob")]
private static extern int sqlite3_bind_blob (IntPtr stmHandle, int iIndex, string iParam, int iBytes, int iOperation);

Usage of the SQLite3 function in C# (Note the function returns 21 - SQLITE_MISMATCH 20 /* Data type mismatch */):

// 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);

Questions:
- Have I imported the sqlite3_bind_blob DLL function correctly with the correct parameter data types?
- Am I using the function correctly, ie, should I be converting the blob to a string and am I correctly obtaining the blob's (byte array's) length?


回答1:


[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);

would be a better signature. Mainly because System.String is a reference to a class with unspecified internal structure, it's not even equivalent to wchar_t**.

With the corrected import, the invocation will look like

int res = sqlite3_bind_blob (stmHandle, 1, blob, blob.Length, SQLITE_TRANSIENT);

and indeed, that's exactly what one of SQLite .NET wrappers do.



来源:https://stackoverflow.com/questions/20182160/am-i-importing-a-sqlite3-c-function-correctly-into-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!