Torsten
Torsten

Reputation: 3

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

I am using the following C# DLL.

    using System;

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

And using it like this in the program:

    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...
        }
    }
}

Only result is "unable to find entry point in DLL" error. My research: I don't have dumpbin in my VS, but I used dotPeek, the result is that the DLL matches the source code. I used Dependency Walker, DLL seems to be fine but it is not pointing out an entry point, screenshot attached.

https://i.sstatic.net/RR4UH.jpg

The program I'm using is a stand-alone third party software, which allows custom file inputs (I can't add DLL references to the actual program). I'm at my wits' end. Any pointers and/or obvious mistakes?

Upvotes: 0

Views: 373

Answers (1)

Sherif Elmetainy
Sherif Elmetainy

Reputation: 4502

As mentioned in comments DllImport is used when interacting with native code.

To call a method in a .NET Dll you have to do the following:

// 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 });

This technique of calling methods by name is called "Reflection". You can google the term "C# Reflection" to find many resources explaining how it works.

Upvotes: 1

Related Questions