Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile Brotli into a DLL .NET can reference

So I'd like to take advantage of Brotli but I am not familiar with Python and C++..

I know someone had compiled it into a Windows .exe. But how do I wrap it into a DLL or something that a .NET app can reference? I know there's IronPython, do I just bring in all the source files into an IronPython project and write a .NET adapter that calls into the Brotli API and exposes them? But actually, I'm not even sure if the Brotli API is Python or C++..

Looking at tools/bro.cc, it looks like the "entry" methods are defined in encode.c and decode.c as BrotliCompress(), BrotliDecompressBuffer(), BrotliDecompressStream() methods. So I suppose a DLL can be compiled from the C++ classes.

like image 478
gt6707a Avatar asked Jan 29 '16 01:01

gt6707a


1 Answers

To avoid the need for Python, I have forked the original brotli source here https://github.com/smourier/brotli and created a Windows DLL version of it that you can use with .NET. I've added a directory that contains a "WinBrotli" Visual Studio 2015 solution with two projects:

  • WinBrotli: a Windows DLL (x86 and x64) that contains original unchanged C/C++ brotli code.
  • Brotli: a Windows Console Application (Any Cpu) written in C# that contains P/Invoke interop code for WinBrotli.

To reuse the Winbrotli DLL, just copy WinBrotli.x64.dll and WinBrotli.x86.dll (you can find already built release versions in the WinBrotli/binaries folder) aside your .NET application, and incorporate the BrotliCompression.cs file in your C# project (or port it to VB or another language if C# is not your favorite language). The interop code will automatically pick the right DLL that correspond to the current process' bitness (X86 or X64).

Once you've done that, using it is fairly simple (input and output can be file paths or standard .NET Streams):

        // compress
        BrotliCompression.Compress(input, output);

        // decompress
        BrotliCompression.Decompress(input, output);

To create WinBrotli, here's what I've done (for others that would want to use other Visual Studio versions)

  • Created a standard DLL project, removed the precompiled header
  • Included all encoder and decoder original brotli C/C++ files (never changed anything in there, so we can update the original files when needed)
  • Configured the project to remove dependencies on MSVCRT (so we don't need to deploy other DLL)
  • Disabled the 4146 warning (otherwise we just can't compile)
  • Added a very standard dllmain.cpp file that does nothing special
  • Added a WinBrotli.cpp file that exposes brotli compression and decompression code to the outside Windows world (with a very thin adaptation layer, so it's easier to interop in .NET)
  • Added a WinBrotli.def file that exports 4 functions
like image 175
Simon Mourier Avatar answered Sep 28 '22 20:09

Simon Mourier