在C#程序中调用C#DLL,找不到入口点

时间:2020-08-23 12:07:28

标签: c#

我正在使用以下C#DLL。

    using System;

namespace LibraryTest
{
    public class Class1
    {
        public int callNr(int nr)
        {
            if (nr == 5)
            {
                return 555;
            }
            return 0;
        }
    }
}

并在程序中像这样使用它:

    using System;
using System.Runtime.InteropServices;

namespace Builder.Store
{
    public class testIndicator : Indicator
    {
        [DllImport(@"C:\LibraryTest.dll", EntryPoint = "callNr")]
        public static extern int callNr(int nr);
        
        public override void Calculate()
        {
            int value = callNr(5);
            
            //do stuff...
        }
    }
}

仅结果是“无法在DLL中找到入口点”错误。 我的研究:我的VS中没有dumpbin,但是我使用了dotPeek,结果是DLL与源代码匹配。 我使用了Dependency Walker,DLL看起来不错,但它并未指出入口点,并附带了屏幕截图。

https://i.stack.imgur.com/RR4UH.jpg

我正在使用的程序是一个独立的第三方软件,该软件允许自定义文件输入(我无法将DLL引用添加到实际程序中)。 我在机智的尽头。有指针和/或明显的错误吗?

1 个答案:

答案 0 :(得分:1)

如注释DllImport所述,在与本机代码交互时使用。

要在.NET Dll中调用方法,您必须执行以下操作:

// First load the assembly
var assembly = Assembly.LoadFrom(@"C:\LibraryTest.dll");

// Get the type that includes the method you want to call by name (must include namespace and class name)
var class1Typetype = assembly.GetType("LibraryTest.Class1");

// Since your method is not static you must create an instance of that class.
// The following line will create an instance using the default parameterless constructor.
// If the class does not have a parameterless constructor, the following line will faile
var class1Instance = Activator.CreateInstance(class1Typetype);

// Find the method you want to call by name
// If there are multiple overloads, use the GetMethod overload that allows specifying parameter types
var method = class1Typetype.GetMethod("callNr");

// Use method.Invoke to call the method and pass the parameters in an array, cast the result to int
var result = (int)method.Invoke(class1Instance, new object[] { 5 });

这种通过名称调用方法的技术称为“反射”。您可以在Google上搜索“ C#反射”一词,以找到许多解释其工作原理的资源。