0

I am attempting to convert established code into a .dll which will be able to be loaded as required by the main program. The .dll does not require any input parameters from the main program and is intended to only return a string value. My primary resource has been this answer.

The dll code is structured:

namespace DLL
{
    class DLLClass
    {                
        public string PublicString(string OutputString)
        {                
           // ... existing code ...
            return OutputString;
        }
    }
}

The main program attempts to load the .dll, execute the logic, and retrieve the returned string for display in the console:

static void Main()
        {
            var DLLPath = new FileInfo("DLL.dll");
            Assembly assembly = Assembly.LoadFile(DLLPath.FullName);
            Type t = assembly.GetType("DLL.DLLClass");
            object obj = Activator.CreateInstance(t);
            MethodInfo method = t.GetMethod("PublicString");
            string TargetString = (string)method.Invoke(obj, null);

            Console.WriteLine("End of dll");
            Console.WriteLine(TargetString);
            Console.ReadLine();
        }

This method presently fails as a TargetParameterCountException ("Parameter count mismatch") occurs at the .Invoke line. The debug information indicates the OutputString remains null at the time of the exception, meaning the code within the .dll does not appear to have run yet.

Thank you in advance for any assistance in this matter.

Community
  • 1
  • 1
Tim B
  • 23
  • 6

1 Answers1

0

Change the below code

string TargetString = (string)method.Invoke(obj, null);

to

object[] parametersArray = new object[] { "Hello" };
string TargetString = (string)method.Invoke(obj, parametersArray);

You are not passing parameter value to the calling method so that it is having such issue.

Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
  • Thank you for your very prompt response. The code now works as intended. I am admittedly still unclear as to why stand-alone code as contained in the .dll itself requires a parameter value to be sent to it in order to function. However, I understand the purpose of SO is to answer, not instruct, so I will use the now-working code as a reference. Your help is certainly appreciated. – Tim B Oct 13 '16 at 06:03