Skip to content

Instantly share code, notes, and snippets.

@brianmed
Last active April 12, 2024 23:32
Show Gist options
  • Save brianmed/8e182d4f5610d9958fa6ff948a96e0ca to your computer and use it in GitHub Desktop.
Save brianmed/8e182d4f5610d9958fa6ff948a96e0ca to your computer and use it in GitHub Desktop.
libmagic example usage in C#
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
// $ c:~/playground/LibMagic>dotnet run -- joy.png
// image/png\012- application/octet-stream; charset=binary
using System.Runtime.InteropServices;
namespace LibMagic;
class Program
{
enum MagicFlags
{
MAGIC_DEBUG = 1,
MAGIC_CONTINUE = 32,
MAGIC_ERROR = 512,
MAGIC_MIME = 1040
};
[DllImport("magic")]
public static extern IntPtr magic_open(int flags);
[DllImport("magic")]
public static extern void magic_close(IntPtr handle);
[DllImport("magic", CallingConvention = CallingConvention.Cdecl)]
public static extern int magic_load(IntPtr handle, IntPtr magic_file);
[DllImport("magic", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr magic_file(IntPtr handle, string input_file);
static void Main(string[] args)
{
IntPtr joy = magic_open((int)(MagicFlags.MAGIC_CONTINUE | MagicFlags.MAGIC_ERROR | MagicFlags.MAGIC_MIME));
magic_load(joy, IntPtr.Zero);
Console.WriteLine(Marshal.PtrToStringAnsi(magic_file(joy, args[0])));
magic_close(joy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment