Question

I am trying to compile an unmanaged dll on the fly using C# CSharpCodeProvider. The compilation is succesful, however, the dll does not work. Here is what I am trying to do:

provOptions.Add("CompilerVersion", "v4.0");
var options = new CompilerParameters();
options.GenerateExecutable = false;
options.CompilerOptions = "/platform:x86 /target:library";
options.ReferencedAssemblies.Add("RGiesecke.DllExport.Metadata.dll");
var provider = new CSharpCodeProvider();
string sourceFile = "tmp2.cs"; 
CompilerResults cr = provider.CompileAssemblyFromFile(options, sourceFile);

an here is C# tmp2.cs:

using RGiesecke.DllExport;
using System.Runtime.InteropServices;
using System;
using System.Text;

class Test
{
  [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
  public static int TestExport(int left, int right)
  {
     return left + right;
  } 
}

What am I doing wrong? Does CSharpCodeProvider not supprt Dllexport? tmp2.cs compile successful in MS VS C# 2012 and works fine.

Was it helpful?

Solution

Actually CSharpCodeProvider does not support DllExport. And neither does the C# compiler Visual Studio uses.

The reason your code works in Visual Studio is because of the UnmanagedExports NuGet package:

A set of compile-time libraries (nothing to deploy) and a build task that enable you to export functions from managed code to native applications.

The second part is important: for it to work, it requires a build task to run. So, if you install the package in Visual Studio, it will run that build task after normal compilation.

But if you just reference the DLL (you do that with CSharpCodeProvider, but it would behave the same if you did just that with VS), it's not going to work.

So, if you want UnmanagedExports to work with CSharpCodeProvider, you will need to figure out some way to run the build task there too. Probably the simplest way would be to just copy the commands from the build task and run them using Process.Start().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top