c# - DLL 函数调用不起作用

标签 c# dll

我创建了一个名为 ClassLibrary1.dll 的 DLL。
它在类 Class1 中只包含一个函数 iscalled()

//Function of DLL
public bool iscalled()
  {
     return true;
  }

现在我创建了一个 WINFORM 的新项目,并在其中添加了我自己的 dll ClassLibrary1 的引用。

下面是winForm代码的代码片段

[DllImport("ClassLibrary1.dll")]
public static extern bool iscalled();


public void mydllcall1()
 {          
     bool ud = iscalled();
     MessageBox.Show(ud.ToString());
 }

当我运行应用程序时,遇到错误,指出

Unable to find an entry point named 'iscalled' in DLL 'ClassLibrary1.dll

我正在寻找一些解决方案。

感谢和问候

苏巴姆·库马尔, 纳斯公司

最佳答案

您无法在 .net 程序集上调用DLLImport。 (DLLImport 属性适用于标准 Dynamic-Link Libraries )。您需要改用 Assembly.Load 或类似的

How to: Load Assemblies into an Application Domain

There are several ways to load an assembly into an application domain. The recommended way is to use the static (Shared in Visual Basic) Load method of the System.Reflection.Assembly class. Other ways assemblies can be loaded include:

  • The LoadFrom method of the Assembly class loads an assembly given its file location. Loading assemblies with this method uses a different load context.

  • The ReflectionOnlyLoad and ReflectionOnlyLoadFrom methods load an assembly into the reflection-only context. Assemblies loaded into this context can be examined but not executed, allowing the examination of assemblies that target other platforms.

示例

public static void Main()
{
    // Use the file name to load the assembly into the current
    // application domain.
    Assembly a = Assembly.Load("example");
    // Get the type to use.
    Type myType = a.GetType("Example");
    // Get the method to call.
    MethodInfo myMethod = myType.GetMethod("MethodA");
    // Create an instance.
    object obj = Activator.CreateInstance(myType);
    // Execute the method.
    myMethod.Invoke(obj, null);
}

进一步阅读

Assembly.Load Method (AssemblyName)

关于c# - DLL 函数调用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49809842/

相关文章:

c# - 转换列表<T>(其中 T : IBar) to ICollection<IBar> fails

c# - 在 Python 脚本中使用 .Net (C#) dll

c# - 如何正确处理 C# - C++ 项目交互?

c# - 用于 C# 的 C++ COM DLL

python - 在 py2exe 构建中包含 PYD/DLL

c# - Unity 为非泛型接口(interface)注册泛型类型

c# - HTTPContext 在 ASP.NET 和 iis express 中找不到客户端 CAC 证书

c# - 将 supportedRuntime 嵌入到 exe 文件中

c# - 我的自定义代理服务器上的 SSL (https) 错误

c# - 无法加载文件或程序集 'Leadtools.Codecs',如果有人熟悉 leadtools