Click here to Skip to main content
Click here to Skip to main content
 

How to create a DLL library in C and then use it with C#

By , 13 Mar 2005
 

Introduction

After spending some time trying to implement this simple task, I started to search similar code examples over the Internet. I was really very surprised when found that all examples were slightly different from what I needed. Finally, I realized that there is no (at least spending 30 min in the net) easy-to-use example, that’s why I decided to write this article.

Assuming that you already know what a DLL is, let's begin with creating a simple one.

  1. Start Visual Studio .NET.
  2. Go to File->New->Project.
  3. Select Visual C++ Project, and from the “Templates”, select “Win32 Project”.
  4. Give the name to your project. This will be the name of your final DLL (in my case: TestLib).
  5. Press OK.
  6. Select DLL from “Application Type” (“Application Settings” tab).
  7. Check “Empty Project” (we need to create our project from scratch, right?), and press Finish.

OK, now we should attach an empty source file to our blank project.

  1. Start Solution Explorer (if it’s not displayed).
  2. Right click to the “Source Files”, Add->Add New Item then select “C++ File” and give the name to it.
  3. Press “Open”.

In the opened window, enter the following code:

#include <stdio.h>

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

Please note that __declspec(dllexport) is an obligatory prefix which makes DLL functions available from an external application.

extern “C” (with brackets) is also very important, it shows that all code within brackets is available from “outside”. Although code will compile even without this statement, during runtime, you’ll get a very unpleasant error. So, do not forget to include it.

Build this application and your DLL will be ready-to-use.

Now it’s time to create an application which will use our DLL, as the main title explains. We will create this type of application using Microsoft’s C#.

Creating a simple C# application:

  1. Start Visual Studio .NET.
  2. Go to File->New->Project.
  3. Select Visual C# Project. From the “Templates”, you can either select “Console Application”, or an “Empty Project” just like it was described above.
  4. Give the name to your application.
  5. Press OK.

Into the specified class, insert the following two lines:

[DllImport("TestLib.dll")]

public static extern void DisplayHelloFromDLL ();

In C#, keyword extern indicates that the method is implemented externally.

Your code should look something like this:

using System;
using System.Runtime.InteropServices;     // DLL support

class HelloWorld
{
    [DllImport("TestLib.dll")]
    public static extern void DisplayHelloFromDLL ();

    static void Main ()
    {
        Console.WriteLine ("This is C# program");
        DisplayHelloFromDLL ();
    }
}

Please, note that System.Runtime.InteropServices is required for operations with the DLL.

According to MSDN:

“The System.Runtime.InteropServices namespace provides a collection of classes useful for accessing COM objects, and native APIs from .NET”

OK, now build this application, and then copy the previously built DLL into the Debug/Release directory of the current application. The DLL should be in the same directory as your main application.

Now start an application. If everything you’ve made was correct, you should get something like this:

That’s all, really simple isn’t it?

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Vladimir Tskhvaradze
Other
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberJoe DF28 Apr '13 - 9:13 
Great! Big Grin | :-D
QuestionGreat!memberJoe DF24 Apr '13 - 19:02 
Thank you So much ! Big Grin | :-D
QuestionSimplest Methodmembersourabhdev141 Mar '13 - 8:40 
The simplest method is to use the following link
 
http://dotnetaid.com/2013/03/01/c-net-creating-dll-to-hide-your-code/[^]
AnswerRe: Simplest Method [modified]memberJibesh1 Mar '13 - 9:25 
The link provided by you is no were related to this article. This article says how to use a C/C++ dll in C# and your link says C# dll to a C# application. out of topic link. I down vote your comment. sorry.


modified 1 Mar '13 - 15:31.

GeneralMy vote of 5memberraj23karthik19 Oct '12 - 19:35 
Thanks
GeneralMy vote of 5memberMember 200288416 Oct '12 - 22:06 
Great for stat up quickly...
Questionopencv c program run in c#membersampathbc1231 Aug '12 - 19:17 
I made a dll form opencv c program. Then i exported it to C# as u said. But i didn't work .It gave error message as follow.
--------------------------------------------------------------------------------
error
An unhandled exception of type 'System.AccessViolationException' occurred in helloworld.exe
 
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
 
------------------------------------------------------
So how can i run opencv c program in c#???
Thank u
GeneralMy vote of 5memberMenon Santosh27 Jul '12 - 3:09 
Good Work
GeneralMy vote of 5memberAVardhan16 May '12 - 5:04 
Good one to start with
GeneralMy vote of 5member5cw24 Apr '12 - 19:15 
Clear, well written, and worked immediately.
 
You should write a follow-on article where you write a C function that takes a cingle input variable and returns a result back to the C# program.
QuestionHoe to get return from parameter of VC++ functionmemberRamveer Singh from Gurgaon, Haryana13 Apr '12 - 0:35 
Hi
 
This tutorial is really good for start.
I need one help. I wan to pass function parameter as call by reference. Means want some return information from function parameter.
How can i do this.
GeneralMy vote of 4memberPradeep Kumar G M20 Mar '12 - 21:57 
I am struggling since couple of days to know how to use C/C DLL in C# application, this article gave me a good knowledge on this...
Thanks a lot Smile | :)
QuestionWe need to create our project from scratch, right?memberSam Hobbs8 Feb '12 - 13:29 
The article asks "we need to create our project from scratch, right?"?
 
The answer is no, we do not need to create our project from scratch. Some of what is in this article will be done for us automatically and more usefully if we leave the checkbox unchecked for creating an empty project and by checking the checkbox for exporting symbols. When we choose the checkbox for exporting symbols, a nice little macro is generated that makes use of __declspec easier.
 
I highly recommend that beginners do not select the option to create an empty project and that they also select the option to generate symbols.
QuestionThanksmemberJayawant Karale29 Nov '11 - 19:11 
Hi,
 
   Thanks for very useful article
GeneralMy vote of 5memberweifirst3 Aug '11 - 21:03 
very good! thank you!
Questioni want to call my function inside the dll and from my applicationmemberMember 77180056 Jul '11 - 18:48 
Lets assume
 
..........
.........
__declspec(dllexport) int Display()
{
return 9;
}
..................
.........
void callinsidethedll()
{
int i=Display(); ///How to do it?
}
Questioni want to call my function inside the dll and from my applicationmemberMember 77180056 Jul '11 - 18:47 
Lets assume
 
..........
.........
__declspec(dllexport) int DisplayHelloFromDLL()
{
return 9;
}
..................
.........
void callinsidethedll()
{
int i=displayHelloFromDll(); ///How to do it?
}
GeneralMy vote of 5membershynet22 Apr '11 - 10:24 
Really great, thank you for you clear explanation!
GeneralMy vote of 5memberMartin Hofmann19 Jan '11 - 4:33 
simple, easy to understand, works! Thanx
GeneralMy vote of 5memberir17528 Oct '10 - 8:04 
Clear, simple, it works.
GeneralMy vote of 5memberSomanth csad16 Aug '10 - 23:59 
So Important,Very good very Nice!!!!
Generalhi.. this dint work for me. [modified]memberaju89628 Jul '10 - 2:09 
getting error.. in C# application.
 
Unable to load DLL 'TestLib.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
 

and two errors in testLib.cpp file.. -->
 
Error 1 error C2059: syntax error : 'string' c:\documents and settings\aju\my documents\visual studio 2008\projects\testlib\testlib\testlib.cpp 4 TestLib
 
OR(without this line--> "extern "c" )
 
Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup MSVCRTD.lib TestLib
 

Error 2 fatal error LNK1120: 1 unresolved externals C:\Documents and Settings\Aju\My Documents\Visual Studio 2008\Projects\TestLib\Debug\TestLib.exe 1 TestLib

modified on Wednesday, July 28, 2010 8:18 AM

GeneralThank youmemberOmar Gamil21 Jun '10 - 23:56 
Really helpful..been looking for this
GeneralGreat JobmemberAbdulkarim Zrik7 Jun '10 - 22:20 
Thank you, its helpful.
 
Sincerely
Abdulkarim Zrik
ABOOOD is the King

Generalhi brothermemberGogu Ologu1 Jun '10 - 13:39 
can you give me one of your instant messengers id ? i wanna ask u some questions wich can be helpfull in real time, althought if u have sufficient time , also i promise i wont stress u with anything when u are busy . regards and best wishes.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 14 Mar 2005
Article Copyright 2005 by Vladimir Tskhvaradze
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid