C#: Replace P/Invoke with delegate pointers

- Moves interop functions to UnmanagedCallbacks struct that
  contains the function pointers and is passed to C#.

- Implements UnmanagedCallbacksGenerator, a C# source generator that
  generates the UnmanagedCallbacks struct in C# and the body for the
  NativeFuncs methods (their implementation just calls the function
  pointer in the UnmanagedCallbacks). The generated methods are needed
  because .NET pins byref parameters of native calls, even if they are
  'ref struct's, which don't need pinning. The generated methods use
  `Unsafe.AsPointer` so that we can benefit from byref parameters
  without suffering overhead of pinning.

Co-authored-by: Raul Santos <raulsntos@gmail.com>
This commit is contained in:
Ignacio Roldán Etcheverry 2022-08-05 03:32:59 +02:00
parent 186d7f6239
commit 2c180f62d9
21 changed files with 1314 additions and 740 deletions

View file

@ -95,13 +95,6 @@ Error CSharpLanguage::execute_file(const String &p_path) {
return OK;
}
extern void *godotsharp_pinvoke_funcs[186];
[[maybe_unused]] volatile void **do_not_strip_godotsharp_pinvoke_funcs;
#ifdef TOOLS_ENABLED
extern void *godotsharp_editor_pinvoke_funcs[28];
[[maybe_unused]] volatile void **do_not_strip_godotsharp_editor_pinvoke_funcs;
#endif
void CSharpLanguage::init() {
#ifdef DEBUG_METHODS_ENABLED
if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
@ -112,12 +105,6 @@ void CSharpLanguage::init() {
}
#endif
// Hopefully this will be enough for all compilers. Otherwise we could use the printf on fake getenv trick.
do_not_strip_godotsharp_pinvoke_funcs = (volatile void **)godotsharp_pinvoke_funcs;
#ifdef TOOLS_ENABLED
do_not_strip_godotsharp_editor_pinvoke_funcs = (volatile void **)godotsharp_editor_pinvoke_funcs;
#endif
#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
// Generate the bindings here, before loading assemblies. The Godot assemblies
// may be missing if the glue wasn't generated yet in order to build them.
@ -1094,8 +1081,12 @@ void CSharpLanguage::_on_scripts_domain_about_to_unload() {
void CSharpLanguage::_editor_init_callback() {
// Load GodotTools and initialize GodotSharpEditor
int32_t interop_funcs_size = 0;
const void **interop_funcs = godotsharp::get_editor_interop_funcs(interop_funcs_size);
Object *editor_plugin_obj = GDMono::get_singleton()->get_plugin_callbacks().LoadToolsAssemblyCallback(
GodotSharpDirs::get_data_editor_tools_dir().plus_file("GodotTools.dll").utf16());
GodotSharpDirs::get_data_editor_tools_dir().plus_file("GodotTools.dll").utf16(),
interop_funcs, interop_funcs_size);
CRASH_COND(editor_plugin_obj == nullptr);
EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(editor_plugin_obj);