I'm trying to write a wrapper around a method with this signature:
[DllImport("SDL2.dll", CallingConvention = CallingConvention.Cdecl)]
internal static extern unsafe Window* SDL_CreateWindow(string title, int x, int y, int w, int h, WindowFlags flags);
You will notice it returns a pointer to a Window
which is a struct.
If I expose this method as-is, then any code that uses it will have to be marked as unsafe, which I would prefer to avoid. As such, I've written a public wrapper method that de-references it:
public static unsafe Window CreateWindow(string title, int x, int y, int w, int h, WindowFlags flags)
{
return *SDL_CreateWindow(title, x, y, w, h, flags);
}
But I'm not 100% sure what this is doing now. The DLL is creating the Window
object; when I de-reference it, is it copied back into a managed value-type object?
I was surprised to find I could pass references in place of pointers, as this worked perfectly:
[DllImport("SDL2.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_DestroyWindow")]
public static extern void DestroyWindow(ref Window window);
But I can't do that for return types. Regardless though, is it safe to do this? I figured by de-referencing and then re-referencing the Window
when I pass it back into DestroyWindow
, the DLL wouldn't be able to find the correct object to destroy as the memory would have been shifted around; but seeing as that the code runs perfectly, I guess this is fine?
(Actually, after looking at how the struct is defined, I see that it has an "id" which I assume it uses as the handle, not the pointer itself)