Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET DllImport Causes App to Quit

I heavily suspect my problem is due to some security issue but here's the full description just in case I'm mistaken.

I have a DLL that was originally written in C (not C++). I'm using DllImport to call the methods in this library. A declaration looks something like this:

[DllImport(@"MyAntiquatedLibrary.dll")
[SecurityPermission(SecurityAction.Assert, Unrestricted = true)]
internal static extern void GetConnectionString(string port, string server, string instance, [Out] StringBuilder output);

The C declaration in the header file looks like this:

void GetConnectionString(const char far *Portname, const char far *ServerName const char far *InstanceName, char far *retConnectionName);

So I created a sample page in my WebApplication project in visual studio whose code-behind looks like this:

protected void Page_Load(object sender, EventArgs e)
{
  try
  {
    var connectionString = new StringBuilder();
    GetConnectionString(null, "myHost", "myInstance", connectionString);
    MyLabel.Text = connectionString.ToString();
  }
  catch(Exception ex)
  {
    MyLabel.Text = string.Format("Something went wrong: {0}", ex.Message);
  }
}

When I debug the program and step past the GetConnectionString() method call I get an:

AccessViolationException was unhandled.
Attempted to read or write protected memory.  This is often an indication that other memory is corrupt.

I see the same issue with any calls I make to the interop DLL from a web service or webpage in my WebApplication project. The same sequence of calls works fine in a ConsoleApplication I wrote when testing this.

The same code works fine when called from a WindowsConsole app. The example is simplified a bit from the actual usage, but the results are the same. In the real solution I have a project that is just in charge of managing the interactions with the C-API and that is what my webservice is calling, but I've run the example above and get the behavior I've explained.

like image 886
Corith Malin Avatar asked Nov 05 '22 21:11

Corith Malin


1 Answers

If your IIS server is running in a 64-bits OS, you should build you project with target CPU = X86 explicitly, otherwise it will be treated as AnyCPU and the jit will probably generate 64 bit native code for it. After doing this you can enable 32 bit applications in IIS and your project should work. Something else to check is that your dll is actually being found by your asp.net application.

like image 90
yms Avatar answered Nov 11 '22 16:11

yms