SQLite Forum

sqlite3_exec: the 3rd argument
Login
Please examine the following code, then say whether you want to continue asserting that there is something amiss worth anybody else's investigation. You may also want to read about the [UnmanagedFunctionPointer](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedfunctionpointerattribute?view=net-5.0)Attribute.

<code>
 using System;
 using System.Runtime.InteropServices;
 namespace ConsoleApp2
 {
   class Program
   {
     const string dbLib = "sqlite3.dll";

     [DllImport(dbLib, EntryPoint = "sqlite3_exec", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
     static extern int sqlite3_exec(IntPtr dbHandle, [In][MarshalAs(UnmanagedType.LPStr)] string sql,
                                    Callback callback, IntPtr arbArg, ref IntPtr errmsg);

     [DllImport(dbLib, EntryPoint = "sqlite3_open", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
     static extern int sqlite3_open([In][MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr dbPtr);

     [DllImport(dbLib, EntryPoint = "sqlite3_close_v2", CallingConvention = CallingConvention.Cdecl)]
     static extern int sqlite3_close_v2(IntPtr dbHandle);

     [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
     internal delegate int Callback(IntPtr p, int n,
                [In][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 1)] string[] names,
                [In][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 1)] string[] values);
 
     static int callCount = 0;

     static void Main(string[] args)
     {
        Callback IR = new Callback(IterateResults);
        IntPtr dbHandle;
        IntPtr errMsg = IntPtr.Zero;

        if (args.Length < 2)
        {
            Console.WriteLine("Provide DB filename and a table name as arguments.");
        }
        else if (0 == sqlite3_open(args[0], out dbHandle))
        {
            int rc = sqlite3_exec(dbHandle, @"select * from " + args[1], IR, dbHandle, ref errMsg);

            Console.WriteLine($"exec return: {rc}");
            sqlite3_close_v2(dbHandle);
        }
        else
        {
            Console.WriteLine("failed to open database");
        }
     }
     public static int IterateResults(IntPtr unused, int n, string[] values, string[] names)
     {
        ++callCount;
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine($"{names[i]}[{callCount}]={values[i]}");
        }
        return 0;
     }
  }
}
</code>