Thursday, 24 June 2010

Common DLL errors

System.DllNotFoundException: Unable to load DLL 'IVL_GR.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
Make sure if you have the DLL in the specified location in the application.


How to create a C# form application and use a DLL

1. Open Visual Studio
2. File->New Project ->Other Languages -> C# -> Windows Application
3. Create your GUI using the toolbox and double click the form to view its code.
4. Add using System.Runtime.InteropServices; in the header
5. Import your DLL using
[DllImport("DLL Name")] in the C# class
above it constructor definition.
3. Declare the exported function(s) of the DLL with keywords public static extern
4. Call the exported function anywhere in the program in the usual manner.
Example:
using System;
using System.Runtime.InteropServices;
public partial class Form1 : Form
{
[DllImport("cppfile.dll")] // the whole path has to be inserted within the quotes
public static extern int abc(); // this should be the function we exported when we created //the DLL

}
call the function abc() anywhere in the usual way you handle a function call.
5. click F5 to run the application.

How to create DLL from CPP file in MS Visual Studio

The process of creating a DLL from a CPP file using visual studio is easy and it requires the following steps.

1. Open visual studio. Go to File->new project -> Visual c++ -> win32 project
2. Give a project name and click ok.
3. Click Application settings and select DLL and click finish.
4. Open the cpp file attached to the project and append your main cpp file to it and add the other source files and header files to the project.
5. Change the name of the main() function in your CPP file to a name you want to use later on while calling the DLL file.
6. If you are using command line arguments and you want to have arguments to be passed to the main() function, load the input pararmeters for the function.
3. Use extern "C" _declspec (dllexport) before the specification of return type of the function.

Example:
Intitially:

int main()
{
//code
}

After following the 3 steps:
extern "C" _declspec (dllexport) int abc(optional input parameters)
{
//code
}
4. Clean up the solution and build it in release mode. You will find your DLL file in the name of the project name in Release folder.