简体   繁体   English

向 C# asp.net 项目添加 DLL 引用后如何调用函数

[英]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”.我有一个名为“MathLibrary”的 C++ dll 项目和一个名为“WebApplication1”的 C# asp.net 项目。 I added the project “MathLibrary” into “WebApplication1” and then I added a reference to MathLibrary.dll (as showed in the figure).我将项目“MathLibrary”添加到“WebApplication1”中,然后添加了对MathLibrary.dll的引用(如图所示)。 But I am not able to call the functions from MathLibrary.dll.但我无法从 MathLibrary.dll 调用函数。 I though I had to add “using MathLibrary” at the top of the .cs file, but the name is not recognized.我虽然必须在 .cs 文件的顶部添加“使用 MathLibrary”,但无法识别名称。 How to call the functions from from MathLibrary.dll?如何从 MathLibrary.dll 调用函数?

WebApplication1网络应用1

MathLibrary.h数学图书馆.h

Managed管理

If MathLibrary.dll is a .NET assembly, you can resolve the issue as follows:如果 MathLibrary.dll 是 .NET 程序集,您可以通过以下方式解决问题:

  • In solution explorer (on the right), locate "WebApplication1" and right click the "references" node.在解决方案资源管理器(右侧)中,找到“WebApplication1”并右键单击“references”节点。
  • Choose "Add reference" then "Projects" (on the left) then "MathLibrary.dll".选择“添加引用”,然后选择“项目”(在左侧),然后选择“MathLibrary.dll”。

Unmanaged非托管

However, from appearances, MathLibrary.dll is NOT a .NET assembly.但是,从表面上看,MathLibrary.dll 不是 .NET 程序集。 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).它似乎是一个标准的 Win32 DLL(我可以从declspec(dllexport)的使用中看出),这意味着它包含非托管代码和一系列符号和入口点(与公开类型的 .NET 程序集 DLL 相反) . If that is the case, setting a reference won't help.如果是这种情况,设置参考将无济于事。 A special procedure is needed to use the DLL, since it is unmanaged.使用 DLL 需要一个特殊的过程,因为它是非托管的。

To learn about consuming ummanaged DLLs from .NET, see this article .要了解如何从 .NET 使用 ummanaged DLL,请参阅此文章

The important bit is:重要的一点是:

Use the DllImportAttribute to identify the DLL and function.使用 DllImportAttribute 来标识 DLL 和函数。 Mark the method with the static and extern modifiers.使用 static 和 extern 修饰符标记方法。

Your C# code might look like this:您的 C# 代码可能如下所示:

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" ).如果您遇到上述问题,您可能需要修改 MathLibrary.dll 导出其符号的方式(您必须使用extern "C" )。

See also How does Extern work in C#?另请参阅Extern在 C# 中如何工作? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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