1

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • How exactly does it not work? What error are you getting? – svick Oct 19 '13 at 22:52
  • @svick If I do a dumpbin /exports on the CSharpCodeProvider compiled DLL, then the DLL has no timestamp or function available. However, the DLL compiled with MSVC 2012 shows a timestamp and a function using dumpbin /exports. – user2855803 Oct 20 '13 at 06:04

1 Answers1

3

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().

svick
  • 236,525
  • 50
  • 385
  • 514
  • Can you tell me more details about this solution ? – Behrooz May 12 '14 at 09:28
  • @Behrooz What kind of details are you looking for? If you have a specific question, it may be best if you asked a new question. – svick May 12 '14 at 22:27
  • Thanks, I need more detail about how can i run a build task using CSharpCodeProvider ? – Behrooz May 29 '14 at 18:15
  • @Behrooz You can't. `CSharpCodeProvider` is just the compiler. Like I said in the answer, a simple way to do this might be `Process.Start()`. – svick May 29 '14 at 18:46