Consuming a C++ DLL in C#
While working on my current project, I had to use some low level I/O operations, but it was difficult using C#, and I got some C++ implementations. Then I thought of creating a DLL in C++ and use it in C#, but I didn’t get any code for the implementation. So I done some searching and I found a solution. It is not a complete solution, but it works
Creating a DLL using C++
For creating a DLL in C++, I was used cl.exe, which comes with .net framework. For the implementation I just wrote simple C++ file.(Simple.cpp)
#include <iostream>
extern "C" __declspec(dllexport) char* Hello();
char* Hello()
{
return "Hello world";
}
I think this is pretty much clear.The extern “C” __declspec(dllexport) allows generate export names automatically. For more details :Exporting from a DLL Using __declspec(dllexport)(MSDN)
After creating this Simple.cpp file, go to Visual Studio Tools > Visual Studio 2008 Command Prompt. Go to the location where you have stored the Simple.cpp file and for compiling and linking C++ file you can use “cl.exe /LD Simple.cpp”.(For more details about cl.exe options checkout : Compiler Options Listed Alphabetically(MSDN) It will compile and Link, and gives a DLL as output.
Consuming a C++ library in C#
When I try to add the DLL by Add Reference, Visual Studio will not allows to add C++ library as Reference. So I tried it with Interop option, by using DLLImportAttribute.
[DllImport(@"D:\Simple.dll", EntryPoint = "Hello")] public extern static string Hello();
Then you can call this function in C# like the following
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Hello());
}
It will display a Messagebox with “Hello World”. Thats it you consumed a C++ DLL in C#.
Issue in the implementation
- I can’t use the DllImport function without the full location. To avoid this I tried to Register the DLL using RegSvr32.But I got some error from RegSvr like this.
The module “D:\Simple.dll” was loaded but the entry-point DllRegisterServer was not found.
Make sure that “D:\Simple.dll” is a valid DLL or OCX file and then try again.
I still exploring the things, I will update once I got the solution for this. Happy Coding
