Monday, August 30, 2010

Calling a function in a DLL from C# code

1. Analyze DLL's function entry point

a. Use "dumpbin.exe" to peek inside the dll's structure.

- We will use command "dumpbin.exe /EXPORT your_dll.dll"
e.g. dumpbin.exe /EXPORTS D:\myDLL\PiEstimatorDLL.dll

- It may be a good idea to write the output into a file
e.g. umpbin.exe /EXPORTS D:\myDLL\PiEstimatorDLL.dll >> dll_export.txt

- NOTE : dumpbin.exe should be installed with your Visual Studio by default.

b. Find function entry point from the output.

- Assume that we want to call PiEstimator.estimatePi() method in the given dll,
we should use "?estimatePi@PiEstimator@@SANH@Z" as the entry point for the function, as underlined in the above screen shot.

2. Use the DLL in your C# code

In your C# code, you should add "DllImport" to import and use your dll functions, such as the following.

[DllImport("PiEstimatorDll.dll", EntryPoint = "?estimatePi@PiEstimator@@SANH@Z"]
public static extern double estimatePi(int numIter);


double piEstimation = estimatePi(numIter);


- NOTE : you should set your PATH environment variable so that the compiler can look up your dll (e.g. PiEstimatorDLL.dll.) Otherwise, you shall give a full path to your dll in DllImport command.

No comments: