0

I wan to import a DLL and use its functions but i want to assign the dll to a value so i dont end up overiding methods

Example of how I want to do it

mydll = [DllImport("MyDll.dll")]
mydll.SayHi();
// So I don't override this:
public void SayHi() { Console.WriteLine("Hello!!!"); }

Any way to acheive this?

4
  • I don't think thats possible without loading the Assembly and using Reflection to call SayHi.
    – Haytam
    Feb 24, 2018 at 19:14
  • Okay, if it is an option it would help a lot as it wouldn't override everything
    – user8493486
    Feb 24, 2018 at 19:17
  • 1
    First, is adding the DLL to your project not an option? That shouldn't override any functions you have.
    – Haytam
    Feb 24, 2018 at 19:21
  • 4
    This question doesn't make any sense. DllImport is an attribute that is applied to a method that tells the runtime where an extern method is implemented in a native dll. If you don't want the name to collide with another method with the same name, put the extern method in another class or rename the method and use the EntryPoint property to specify the name in MyDll.dll. Feb 24, 2018 at 19:33

1 Answer 1

4

Import the DLL in a wrapper class.

using System;
using System.Runtime.InteropServices;

// Namespace is optional but generally recommended.
namespace MyDLLImports
{
    static class MyDLLWrapper
    {
        // Use DllImport to import the SayHi() function.
        [DllImport("mydll.dll", CharSet = CharSet.Unicode)]
        public static extern void SayHi();
    }
}

class Program
{
    static void SayHi()
    {
        // whatever...
    }
    static void Main()
    {
        // Call the different SayHi() functions.
        MyImports.MyDLLWrapper.SayHi();
        SayHi();
    }
}

See the MSDN docs on the DLLImport attribute for further details. You may also need to declare calling conventions, different character encodings, the DLL's main entry point, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.