Thursday, April 21, 2011

Creating a DLL in Visual Studio


This was another subject neglected in my formal schooling. I picked it up through trial and error, but you won’t have to as I’m about to run through an example for you.
In this example I’ll be using Visual Studio 2010 to create a dynamic link library out of a C file and use it in a managed C++ project.
For the C DLL:
Create a Win32 Project. Application type: DLL. Empty Project.
Create your C file. I called mine retnum.c.
The text of my retnum.c is very simple:
__declspec(dllexport) int retnum()
{
        return 5;
}
The __declspec(dllexport) lets the compiler know we want to use this function in a DLL.
For the C++ project.
Lets create a simple CLR Console Application project under the same solution as our C project.
Right click on your solution and go to properties, set startup project to be your C++ project. Also, go to project dependencies, on the “Project” dropdown menu select you C++ project and check off your C project.
Right click on your C++ project and go to properties. Go to Common Properties, Frameworks and References, click “add new reference”. Select your C project.
Create a header file under your C++ project. I called mine cdll.h.
The text of my cdll.h is:
extern "C"
{
   retnum();
}
The extern "C" lets our C++ program know we will be using C code.
The meat of my C++ project was in my app.cpp file. Condense as follows:
#include "stdafx.h"
#include <iostream>
#include "cdll.h"

using namespace System;
using namespace std;

int main(array<System::String ^> ^args)
{
    int i = retnum();
      Console::WriteLine(L"Your number is: "+i);
      cin.get();
    return 0;
}
So, that’s how you create a C DLL and use it in a C++ project in Visual Studio.

Project files now available on the download website.

No comments:

Post a Comment