从DLL调用函数?

问题描述 投票:26回答:4

我是C#的新手,我正在努力学习使用DLL。我正在尝试将我的对象包装在DLL中,然后在我的程序中使用它。

public class Foo   // its in the DLL
{
   public int ID;
   public void Bar()
   {
      SomeMethodInMyProgram();
   } 
}

所以我尝试将其打包到DLL但我不能,因为编译器不知道SomeMethodInMyProgram()是什么。

我想用它像:

class Program // my program, using DLL
{
    static void Main(string[] args)
    {
       Foo test = new Foo();
       test.Bar();
    }
 } 
c# dll interop call dllimport
4个回答
26
投票

通过解决方案资源管理器添加DLL - 右键单击​​引用 - >添加引用然后“浏览”到您的DLL - 然后它应该可用。


39
投票

取决于什么类型的DLL。这是用.NET构建的吗?如果它是非托管代码,那么这里是一个例子,否则Rob的答案将起作用。

非托管C ++ DLL示例:

using System;
using System.Runtime.InteropServices;

您可能需要使用DllImport

[DllImport(@"C:\Cadence\SPB_16.5\tools\bin\mpsc.dll")]
static extern void mpscExit();

要么

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

然后每个人都这样调用:

// a specific DLL method/function call
mpscExit();
// user32.dll is Microsoft, path not needed
MessageBox(new IntPtr(0), "Test", "Test Dialog", 0);  

4
投票

您需要在运行时将DLL实际加载到应用程序中,因此DLL的动态部分。您还需要头文件来定义DLL中的函数,以便您的编译知道已定义的函数。我在这里的知识基于C ++,所以这对C#有用吗我不确定,但它会是这样的......


4
投票

我在这里参加派对已经迟到了,但我正在留下这个答案,因为有人像我一样拔出他/她的头发。所以基本上,在面对这个问题时,我没有VS IDE的奢侈。我正在尝试使用csc通过cmdline编译代码。要引用dll,只需将编译器标志/ r:PathToDll / NameOfTheDll添加到csc即可。

命令看起来像

csc / r:PathToDll / NameOfTheDll / out:OutputExeName FileWhichIsReferencingTheDll.cs

在FileWhichIsReferencingTheDll.cs中添加using namespace AppropriateNameSpace;来访问函数(通过调用class.functionName,如果是静态的,或者通过创建类的对象并在对象上调用函数)。

© www.soinside.com 2019 - 2024. All rights reserved.