Accessing SQLite from Javascript #61
-
Just a question here - my use case is fairly specific, but I'd like to access the same database connection from both Javascript and Unity. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
Yup, that's specific alright. I have alternatives to that, but all of them are much more complex. Please let me know if the JS to C# call works for you. I won't elaborate in case the easy way just works =] |
Beta Was this translation helpful? Give feedback.
-
Ok, so that seems to be the best bet - Using callbacks. mergeInto(LibraryManager.library,
{
RegisterQueryMethod : function(callback)
{
window.SQL = window.SQL || {};
window.SQL.Query = (query) => {
// Convert JS string to Unity-compatible memory pointer
var length = lengthBytesUTF8(query) + 1; // Get string length in bytes (plus null terminator)
var stringMessage = _malloc(length); // Allocate memory
stringToUTF8(query, stringMessage, length) // Write UTF-8 string to allocated memory
// Call the Unity callback
var result = {{{ makeDynCall('ii', 'callback') }}}(stringMessage);
// Release the memory for the query
_free(stringMessage);
// Convert result to JS
var jsString = UTF8ToString(result);
return jsString;
};
}
}); (Likely need to edit this accordingly and add each query you want to execute to the JS Lib, or add an argument for the return type you are expecting) Then in C# [DllImport("__Internal")]
private static extern void RegisterQueryMethod(Func<string, string> callback);
[MonoPInvokeCallback(typeof(Func<string, string>))]
public static string ExecuteQuery(string query)
{
Debug.Log($"C# callback received \"{query}\"");
// TODO: Execute query on the connection here
return "";
} Usage from JS is window.SQL.Query("This is a test") |
Beta Was this translation helpful? Give feedback.
Figure that this works, unless there's a simpler way? Wanted to pool the lists (My own implementation, lists are cleared on release) since this might be called a lot and reducing allocations can't hurt, especially when there's a lot of string allocations already.