开发者

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 seque开发者_运维百科nce 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.


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.


The issue ended up being that I wasn't initializing the C-API correctly. There is a function call which initializes the whole API and while I was doing that in my UnitTests, I forgot to do it in the webservice.

Thank you all for your help though, I feel like I've learned a lot about the ASP.NET security model and .NET trust implementations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜