[GIS] Error Loading spatialite extension in .NET Project using System.Data.SQLite

netspatialite

I am trying to use Spatialite in a .NET application using the
System.Data.SQLite provider.

I have tried to load 'libspatialite-4.dll' but an error happens when I
call function "conn.EnableExtensions(true);conn.LoadExtension("libspatialite-4.dll");"

The specific error is "Attempted to read or write protected memory.
This is often an indication that other memory is corrupt."

I am using sqlite-netFx40-setup-x64-2010-1.0.92.0,libspatialite-4.1.1, VS2010 SP1, .net Framework 4.0, Windows7 64bit,

Best Answer

This is an exception/error that often occurs when you are dealing with unmanaged code i.e. calls to COM Objects or C/C++ .dll files in your .NET code. It is a difficult bug to track down because the error is occurring within the unmanaged code or when you are passing arguments to the unmanaged code. The message:

"Attempted to read or write protected memory. This is often an indication that other memory is corrupt"

is a general exception message and is not always very telling to what the problem really is. Refer to this link, specifically the answer given by Shanks Zen for more info on the topic.

It appears you are not using the correct syntax for calling the .dll which is why you are getting the exception that you are. Here is a code sample from github of how to correctly load spatialite:

using System.Data.SQLite;

using (DbConnection connection = new SQLiteConnection("Data Source=" + database)) {
connection.Open(); // load the extension 
using (DbCommand command = connection.CreateCommand()) {
    //Load the libspatialite library extension - *.dll on windows, *.a on iOS
    command.CommandText = "SELECT load_extension('libspatialite-2.dll');";
    command.ExecuteNonQuery(); // Run queries here
    }
}
Related Question