ShaderLang icon indicating copy to clipboard operation
ShaderLang copied to clipboard

Wrap C++ API in a C API to allow the library to be used in other languages

Open SirLynix opened this issue 2 years ago • 0 comments

Currently, the library part of NZSL cannot be used in other languages due to its C++ API.

It would be a good thing to provide a C wrapper, even minimalistic, to be able to use NZSL in other languages (C, Rust, etc.).

For example

#include <NZSL/Parser.hpp>
#include <NZSL/GlslWriter.hpp>
#include <NZSL/SpirvWriter.hpp>

int main()
{
    nzsl::Ast::ModulePtr shaderAst = nzsl::ParseFromFile("pbr.nzsl");

    nzsl::SpirvWriter spirvWriter;
    std::vector<std::uint32_t> spirv = spirvWriter.Generate(shaderAst);
    // spirv contains SPIR-V bytecode that can be directly given to Vulkan

    nzsl::GlslWriter glslWriter;
    nzsl::GlslWriter::Output output = glslWriter.Generate(shaderAst);
    // output.code contains GLSL that can directly be used by OpenGL
}

would become something like (in C):

#include <CNZSL/Parser.h>
#include <CNZSL/GlslWriter.h>
#include <CNZSL/SpirvWriter.h>

int main()
{
    nzslModule* shaderAst = nzslParseFromFile("pbr.nzsl", nullptr); //< second arg for parameters

    nzslSpirvWriter* spirvWriter = nzslCreateSpirvWriter(nullptr); //< arg for parameters
    uint32_t* spirvOutput = nzslSpirvWriterGenerate(spirvWriter, nullptr);

    nzslGlslWriter* glslWriter = nzslCreateGlslWriter(nullptr);
    const nzslGlslWriterOutput* glslOutput = nzslGlslWriterGenerate(glslWriter, nullptr);
    // output->code contains GLSL that can directly be used by OpenGL

    nzslDestroyGlslWriterOutput(glslOutput);
    nzslDestroyGlslWriter(glslWriter);

    nzslDestroySpirvWriterOutput(spirvOutput);
    nzslDestroySpirvWriter(spirvWriter);

    nzslDestroyModule(shaderAst);
}

SirLynix avatar Aug 22 '23 14:08 SirLynix