5,445,109 members and growing! (15,297 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » .NET Framework » General     Intermediate License: The Code Project Open License (CPOL)

Creating and Calling C Function DLL from .NET

By harunmip

Explain how to call C function DLL from .NET
C, C#, VB, VC6, C++Windows, .NET, .NET 1.0, .NET 1.1, .NET 2.0, Win2K, WinXP, Win2003, ASP.NET, VS.NET2003, VS6, Visual Studio, Dev

Posted: 7 Sep 2004
Updated: 15 Sep 2004
Views: 112,742
Bookmarked: 28 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
12 votes for this Article.
Popularity: 4.39 Rating: 4.07 out of 5
1 vote, 8.3%
1
1 vote, 8.3%
2
1 vote, 8.3%
3
2 votes, 16.7%
4
7 votes, 58.3%
5

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:

#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:

    <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:

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

The code...

int* pnStan

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

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

The code...

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:

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)

About the Author

harunmip



Occupation: Web Developer
Location: Indonesia Indonesia

Other popular .NET Framework articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 13 of 13 (Total in Forum: 13) (Refresh)FirstPrevNext
Subject  Author Date 
Generalmemory leak???memberpradeeppatel20:54 5 Aug '07  
Generalcall C code from C#memberBandoleiro1:35 11 Dec '06  
GeneralCalling From ServicedComponent?memberPyrinoc13:32 21 Nov '06  
GeneralRe: Calling From ServicedComponent?memberEric Engler12:22 4 Jan '07  
GeneralExtra Line needed in VB.NET codememberbetwulf12:21 25 Jul '06  
Generaldll from c?memberjason_limwk23:10 2 Mar '06  
GeneralRe: dll from c?memberLunaSoft Inc.0:55 16 Aug '06  
GeneralThanks for thatmemberRocketDude6:42 10 Dec '05  
GeneralDll Problemmembersrikar11:11 29 Aug '05  
Generalnot rightsussAnonymous9:56 14 Sep '04  
GeneralCome onmembernorm.net1:19 8 Sep '04  
GeneralRe: Come onmemberhelitb1:42 8 Sep '04  
GeneralRe: Come onmembernorm.net1:50 8 Sep '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Sep 2004
Editor: Deeksha Shenoy
Copyright 2004 by harunmip
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project