Wednesday, September 2, 2009

Problems with Native DLLs, DllImport, and ASP.NET

I have long had a problem when using ASP.NET where my native Dlls can't be found when the .NET Assembly calls a function from the native Dll. The only solution I have been able to find is to put the native DLLs in a directory that is in the system PATH (or in a directory that is already in the PATH like Windows\system32). I have searched the internet many times and finally found a posting that explains why even if there doesn't appear to be a good solution:

Stephen Cheng explains that the .NET assemblies are copied to a ASP.NET temporary directory before they are are run. Since the .NET assemblies really don't know anything about the native .DLLs, the native DLLs don't get copied. When the .NET assembly tries to use a method in the native DLL, it is not there and you get the error message:

"An exception of type 'System.EntryPointNotFoundException' occurred in xxx.DLL but was not handled in user code Additional information: Unable to find an entry point named 'xxxx' in DLL '.\xxx.dll'."

It doesn't matter that the Native dll is in your ASP.NET project's bin directory, because that is not where it is run from.

The solutions given are to use LoadLibrary to get the dll loaded into memory, but you have to know where it is. You can turn the shadowCopyBinAssemblies off in the web.config file, but this has problems. And finally, you can add the location of the native dll to the system PATH.

If any one knows of a better solution, please post a comment.

No comments: