Sometimes, unfortunately, you have to use some old code in a new project. Or, simplier, someone-else-code is in C and you work in C# (or VB.NET) and so… whatever is the cause, if you have to use some C code in a .NET project, read this! 😉

My example is in C#, but for VB.NET is almost the same.

First of all, create a C++ file (.cpp) and write your C code. It must be written in this way:

#include <stdio.h>

extern "C"
{
	__declspec(dllexport) void DisplayHelloFromDLL()
	{
		printf("Hello from DLL !\n");
	}

	__declspec(dllexport) int __stdcall adddll(int a, int b)
	{
		return a+b;
	}
}

As you can see, there are some key words. All of them are needed for use these functions from the extern. This is similar to the “Public” in .NET.

Then, you compile and create the dll file.

After this, you have to use it from a C# project.

Write this:

[DllImport("sampleAdd.dll")]
public static extern void adddll(int a, int b);

In this way, the compiler will look for the sampleAdd.dll, because it knows it is defined extenarly, in that file. The dll must be in the same folder of the program; so, when you are using Visual Studio, it has to be in the folder debug or release.

Finally, you can use the add function:

int c = adddll(3,4); //c = 3 + 4

If you’d like to go deeper, you can read this.

Advertisements