Option 1: .NET InstallUtil (part of the normal .NET install)
Add a reference to System.Configuration.Install
then drop something like this in your assembly:
[System.ComponentModel.RunInstaller(true)]
public class Sample : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
this.Context.LogMessage("This can be in a .dll.");
// Do your thing...
}
}
Then abuse the .NET InstallUtil:
%windir%\Microsoft.NET\Framework\v2.0.50727\installutil /logtoconsole=false /logfile= /u [your assembly .dll here]
It may be a bit messy, especially without all the command line parameters disabling logging.
Option 2: use native rundll32 to inverse P/Invoke a static class method
2016 Edit: Now a Nuget package: UnmanagedExports (src)!
Unknown MSIL directives (msdn forum, 2007) links to a beta 1 release of the IL Assembly Language Programmer's Reference (10/3/2000, pg.74) which states:
If fromunmanaged is specified, the
runtime will automatically generate a
thunk that will convert the unmanaged
method call to a managed call, call
the method, and return the result to
the unmanaged environment.
There is more detail in Expert .NET 2.0 IL assembler and Inside Microsoft. NET IL Assembler. (Best search keywords: ilasm vtentry).
Related reading:
Unmanaged Exports: Cannot compile assembly (stackoverflow, 2010)
Unmanaged Exports / RGiesecke.DllExport.dll (stackoverflow, 2010)
Create a C# DLL That Can Be Imported in a Delphi App Using stdcall (stackoverflow, 2009)
C# Project Template for Unmanaged Exports (Robert Giesecke, 2010) - msbuild, vs2010 integration
IKVM.Reflection Update: export static managed methods as unmanaged DLL exports (mono, 2011)
Simple Method of DLL Export without C++/CLI (codeproject, 2009) - no 64-bit support?
How to Automate Exporting .NET Function to Unmanaged Programs (codeproject, 2006) - supports 64-bit
Has anything been added to .Net 4.0 to support "Reverse P/Invoke" scenarios? (msdn forum, 2010) - code listing
Unmanaged code can wrap managed methods (codeproject, 2004)
Potential drawbacks:
Gotchas with Reverse Pinvoke (unmanaged to managed code callbacks) (msdn blog, 2006)
Reverse P/Invoke and exception (msdn blog, 2008)