How to call a dll function in C#?

Posted on 2008-11-19
Last Modified: 2013-12-17
I am new to C#.   I am try to test out my dll using C# Window Form application. Is there any reference that someone has that show how to declare and use  the DLL functions  within C# application
Question by:xewoox
    LVL 26

    Expert Comment

    by:Anurag Thakur
    what kind of dll are you talking about
    a .net dll (which is actually an assembly) or a com dll
    LVL 2

    Accepted Solution

         Here you want to use Managed code from UnManaged code(in VC++ )

    The Extract from MSDN might help you. There are Possibly 3 Ways

    1)Directly Accessing a Managed API
    If an unmanaged client is written in C++, it can be compiled with the Visual Studio .NET C++ compiler as a "mixed mode image." After this is done, the unmanaged client can directly access any managed API. However, some coding rules do apply to accessing managed objects from unmanaged code; check the C++ documentation for more details.
    Direct access is the preferred option since it does not require any special consideration from managed API developers. They can design their managed API according to managed API design guidelines (DG) and be confident that the API will still be accessible to unmanaged callers.

    2) Exposing a Managed API as a COM API
    Every public managed class can be exposed to unmanaged clients through COM interop. This process is very easy to implement, because the COM interop layer takes care of all the COM plumbing. Thus, for example, every managed class appears to implement IUnknown, IDispatch, ISupportErrorInfo, and a few other standard COM interfaces.
    Despite the fact that exposing managed APIs as COM APIs is easy, managed and COM object models are very different. Therefore, exposing managed API to COM should always be an explicit design decision. Some features available in the managed world have no equivalent in the COM world and will not be usable from COM clients. Because of this, there is often tension between managed API design guidelines (DG) and compatibility with COM.
    If COM clients are important, write your managed API according to the managed API design guidelines, and then write a thin COM-friendly managed wrapper around your managed API that will be exposed to COM.

    3)Exposing a Managed API as a Flat API
    Sometimes unmanaged clients cannot use COM. For example, they might already be written to use flat APIs and cannot be changed or recompiled. C++ is the only high-level language that allows you to expose managed APIs as flat APIs. Doing this is not as straightforward as exposing a managed API as a COM API. It is a very advanced technique that requires advanced knowledge of C++ interop and the differences between the managed and unmanaged worlds.

    Expose your managed API as a flat API only if absolutely necessary. If you have no choice, be sure to check the C++ documentation and be fully aware of all the limitations.

    Reffer :

    LVL 1

    Assisted Solution

    Hi xewoox,

    Assuming you've created the DLL and want to access its methods:

    1. Right click on your project you want to add the reference to.
    2. Add Reference
    3. Browse to your DLL -> Add it.
    4. In the Using declarations add: Using YourDllNameHere;
    5. To access it, just call the class it encapsulates. I.e. MyClass myClass = new MyClass();


    Author Comment

    It is an unmanaged code dll.  It is originally compiled under Visual Studio 6 as an MFC Dll
    LVL 2

    Assisted Solution

    Use DllImport. There is a sample attached. It's cryptic but there are lots of samples available on the internet. This one is an extract from a TestBench in c# that was written to prove a C++ unmanaged dll.
    Note tha conversion between data types. The dll used LPSTR.
    using System;
    using System.Runtime.InteropServices;
    using System.Text;
    namespace Wrapper
        public class WrapperClass
    	[DllImport("DevName", CallingConvention=CallingConvention.Cdecl )]
    		public static extern int dllOpenDevice( 
    		[MarshalAs(UnmanagedType.LPArray)] byte[] ProductRef,
    		[MarshalAs(UnmanagedType.LPArray)] byte[] SWDesc,
    		[MarshalAs(UnmanagedType.LPArray)] byte[] SensorDesc );
    		[DllImport("DevName", CallingConvention=CallingConvention.Cdecl )]
    		public static extern int dllCloseDevice();
        public static int OpenDevice( ref String ProductRef,
                                      ref String SWDesc,
                                      ref String SensorDesc )
            byte[] bProductRef = new byte[MAX_MSGLEN];
            Int32 iRet = dllOpenDevice( bProductRef, ..............
            if( iRet == 0 )
                ProductRef = System.Text.Encoding.ASCII.GetString( bProductRef ............... );

    Open in new window


    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
    We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now