问题
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