繁体   English   中英

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

[英]Calling a C# DLL in a C# program, entry point not found

我正在使用以下 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 引用)。 我不知所措。 任何指针和/或明显的错误?

正如评论中提到的,在与本机代码交互时使用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 });

这种按名称调用方法的技术称为“反射”。 您可以在谷歌上搜索术语“C# 反射”以找到许多解释其工作原理的资源。

暂无
暂无

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

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