dotnet / Silk.NET

The high-speed OpenGL, OpenCL, OpenAL, OpenXR, GLFW, SDL, Vulkan, Assimp, WebGPU, and DirectX bindings library your mother warned you about.
https://dotnet.github.io/Silk.NET
MIT License
3.88k stars 378 forks source link

Silk.NET.Vulkan work on iOS? #2206

Closed xtuzy closed 4 weeks ago

xtuzy commented 1 month ago

I try load Vk.GetApi() on iPad will throw message "Value cannot be null. (Parameter 'libraryPath')'", it like DefaultNativeContext.TryCreate() is wrong.

I try custom NativeContext

INativeContext CreateIOSContext(string text = "__Internal")
{
    var _foldSilkNETVulkanVkPInvokeOverride0 = AppContext.TryGetSwitch("SILK_NET_VULKAN_VK_ENABLE_PINVOKE_OVERRIDE_0", out var isEnabled) && isEnabled;
    if (_foldSilkNETVulkanVkPInvokeOverride0 && text == "__Internal")
    {
        return null;
    }
    if (IOSNativeContext.TryCreate(text, out var context))
    {
        return context;
    }

    throw new FileNotFoundException("Could not load from any of the possible library names! Please make sure that the library is installed and in the right place!");
}

class IOSNativeContext : INativeContext, IDisposable
{
    private readonly IntPtr _libraryHandle;

    public IntPtr NativeHandle => _libraryHandle;

    public static bool TryCreate(string name, out IOSNativeContext context)
    {
        var library = ObjCRuntime.Dlfcn.dlopen(null, 0x002);//主程序 copy from xamarin-macios

        context = new IOSNativeContext(library);
        return true;
    }

    IOSNativeContext(IntPtr library)
    {
        _libraryHandle = library;
    }

    public nint GetProcAddress(string proc, int? slot = null)
    {
        return ObjCRuntime.Dlfcn.dlsym(NativeHandle, proc);
    }

    public bool TryGetProcAddress(string proc, out nint addr, int? slot = null)
    {
        addr = ObjCRuntime.Dlfcn.dlsym(NativeHandle, proc);
        return true;
    }

    public void Dispose()
    {
        ObjCRuntime.Dlfcn.dlclose(NativeHandle);
    }
}

then by my GetApi() method get Vk, it work well.

IMG20240531234339

Vk GetApi()
{
    var context = CreateIOSContext();
    Vk ret = new Vk(context);

    return ret;
}
Perksey commented 1 month ago

Hey, it’s cool you were able to figure our internals like that! In your csproj make sure TrimMode is set to full and Trimming is set to enable, and it should work when building for release.

Note that iOS support is still experimental and we do not make guarantees that it will work.