简体   繁体   中英

How to call functions after adding DLL reference to a C# asp.net project

I have a C++ dll Project called “MathLibrary” and a C# asp.net Project called “WebApplication1”. I added the project “MathLibrary” into “WebApplication1” and then I added a reference to MathLibrary.dll (as showed in the figure). But I am not able to call the functions from MathLibrary.dll. I though I had to add “using MathLibrary” at the top of the .cs file, but the name is not recognized. How to call the functions from from MathLibrary.dll?

WebApplication1

MathLibrary.h

Managed

If MathLibrary.dll is a .NET assembly, you can resolve the issue as follows:

  • In solution explorer (on the right), locate "WebApplication1" and right click the "references" node.
  • Choose "Add reference" then "Projects" (on the left) then "MathLibrary.dll".

Unmanaged

However, from appearances, MathLibrary.dll is NOT a .NET assembly. It appears to be a standard Win32 DLL (I can tell from the use of declspec(dllexport) ), meaning that it contains unmanaged code and a series of symbols and entry points (as opposed to a .NET assembly DLL, which exposes types). If that is the case, setting a reference won't help. A special procedure is needed to use the DLL, since it is unmanaged.

To learn about consuming ummanaged DLLs from .NET, see this article .

The important bit is:

Use the DllImportAttribute to identify the DLL and function. Mark the method with the static and extern modifiers.

Your C# code might look like this:

namespace WebApplication1
{
    class ExternalFunctions
    {
        [DllImport("MathLibrary.dll")]
        public static extern bool fibonacci_next();
    }

    class Program
    {
        static void Main()
        {
            //call it
            var foo = ExternalFunctions.fibonacci_next();
        }
    }
}

If you have trouble with the above, you may need to modify the way that MathLibrary.dll exports its symbols (you must use extern "C" ).

See also How does Extern work in C#? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM