Click here to Skip to main content
16,016,489 members
Articles / Web Development / ASP.NET
Article

Creating and Calling C Function DLL from .NET

Rate me:
Please Sign up or sign in to vote.
4.47/5 (14 votes)
15 Sep 2004CPOL2 min read 238.3K   6.3K   44   16
Explain how to call C function DLL from .NET

Introduction

I will give an example of how to create a C DLL function and call it from VB.NET. It is simple but there are some tasks that you have to do.

First, create a C DLL Project. Use VC++ 6, from the File new project wizard, choose Win32 Dynamic-Link Library, click OK. Select an Empty DLL Project, because we just want to create a simple DLL. Click next.

Now add some files. From File new, select Files tab, select C++ Source File, name it for example Simple.c. Repeat the last step by creating Simple.def file.

Double click Simple.c and add the following code:

C++
#include <WINDOWS.H>

      LPCSTR DisplayStringByVal(LPCSTR pszString)
      {
          return "Hallo apa kabar ";
      }

    void ReturnInParam(int* pnStan, char** pMsg)
    {
        long *buffer;
        char text[] = "Hallo ";
        char name[sizeof(*pMsg)];
         strcpy(name, *pMsg);
        *pnStan = *pnStan + 5;

        buffer = (long *)calloc(sizeof(text)+sizeof(*pMsg), sizeof( char ) );
        *pMsg = (char *)buffer;

        // do not free the buffer, because it will be used by the caller
        // free( buffer );
         strcpy(*pMsg, text);
         strcat(*pMsg, name);
      }

The first function simply returns the string "Hallo apa kabar" without processing anything. The second function adds "Hello" in front of the pMsg parameter and adds the pnStan parameter with 5. For example, if you call the second function from VB.NET code as below:

VB.NET
<DllImport("E:\Temp\simple.dll", CallingConvention:="CallingConvention.Cdecl)"> _
Private Shared Sub ReturnInParam(ByRef Stan As Integer, _
    ByRef Message As String)
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    Dim Num As Integer = 8
    Dim Message As String = "Harun"
    ReturnInParam(Num, Message)
    MessageBox.Show(Message)
End Sub

After you call the function, the Num variable value is 13, and the message box will prompt Hello Harun.

Here is an explanation of some important things in the code. Let's see the function declaration in C:

C++
void ReturnInParam(int* pnStan, char** pMsg)

The code...

C++
int* pnStan

... indicates that you want to pass the parameter by reference, not by value. You can see this in the VB code:

VB.NET
Private Shared Sub ReturnInParam(ByRef Stan As Integer, _ ... 

The code...

C++
char** pMsg 

... also indicates the same thing. The reason I put two asterisks (*) here is because .NET translates char* with a single quote as string and passes the parameter by value. So, if I want to pass the string by reference (or as a pointer), then I have to put another asterisk.

The rest of the C code is about adding 5 to pnStan and "Hello" at the beginning of pMsg. You must know C to understand the code.

Before you compile the C file, there is a final step that needs to be done:
Define the library and function in the Simple.def file as follows:

VB.NET
LIBRARY Simple
      DESCRIPTION 'Sample C DLL for use with .NET'
      EXPORTS
        DisplayStringByVal
        ReturnInParam

This tells VB where to locate the function Entry Point. If you don't provide this declaration, then you will get a message just like this:

An unhandled exception of type 'System.EntryPointNotFoundException' 
    occurred in Call_C_dll.exe

Additional information: Unable to find an entry point named ReturnInParam 
    in DLL E:\Temp\simple.dll.

Well, that's all, simple isn't it?

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Indonesia Indonesia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generali get an error when i use the code in visual studio 2008 Pin
mlov838-Jan-11 7:27
mlov838-Jan-11 7:27 
Generalcall functions in a dll made with VB 2005 in a VB 2003 project Pin
murad198522-Nov-08 22:46
murad198522-Nov-08 22:46 
QuestionHow to call this function Pin
Muneer Safi18-Nov-08 2:35
Muneer Safi18-Nov-08 2:35 
dear harunmip

i have this C function

int BII_Read_Transaction_Log (int option, int updateFlag, int maxEntries,
unsigned char *log)

*log A pointer to a buffer to hold the Transaction Log data.

how can use it in vb.net or c#

Please Help
Questionmemory leak??? Pin
pradeeppatel5-Aug-07 19:54
pradeeppatel5-Aug-07 19:54 
Generalcall C code from C# Pin
Bandoleiro11-Dec-06 0:35
Bandoleiro11-Dec-06 0:35 
QuestionCalling From ServicedComponent? Pin
Pyrinoc21-Nov-06 12:32
Pyrinoc21-Nov-06 12:32 
AnswerRe: Calling From ServicedComponent? Pin
Eric Engler4-Jan-07 11:22
Eric Engler4-Jan-07 11:22 
GeneralExtra Line needed in VB.NET code Pin
John Placais25-Jul-06 11:21
John Placais25-Jul-06 11:21 
Questiondll from c? Pin
jason_limwk2-Mar-06 22:10
jason_limwk2-Mar-06 22:10 
AnswerRe: dll from c? Pin
Sphyr15-Aug-06 23:55
Sphyr15-Aug-06 23:55 
GeneralThanks for that Pin
RocketDude10-Dec-05 5:42
RocketDude10-Dec-05 5:42 
GeneralDll Problem Pin
srikar129-Aug-05 0:11
srikar129-Aug-05 0:11 
Generalnot right Pin
Anonymous14-Sep-04 8:56
Anonymous14-Sep-04 8:56 
GeneralCome on Pin
NormDroid8-Sep-04 0:19
professionalNormDroid8-Sep-04 0:19 
GeneralRe: Come on Pin
harunmip8-Sep-04 0:42
harunmip8-Sep-04 0:42 
GeneralRe: Come on Pin
NormDroid8-Sep-04 0:50
professionalNormDroid8-Sep-04 0:50 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.