Tutorial - C# / Mono - C++ DLL Objects accessed from C#


Coding Friends Tutorial Index - > C# / Mono

Author Ian - Tutorial Posts = 62
Because there is a few things that c# cannot do compared to c++, e.g. cpu/memory management. And also there is probably allot of dll’s out there are still required for some events, c# is able to communicate with these files and use there functions within the c# language.

To create an dll within Visual Studio 2005 within the language c++, if you do the following

1. New project -> c++ -> empty project
2. Enter project name (e.g. hellocdll)
3. Right click source files ( in the solution explorer) add-> new item
enter an cpp filename.
4, Right click on the main project heading in the solution explorer -> properties
configuration properties->general inner screen project defaults -> configuration type, alter to dynamic library (.dll)
5. Copy and paste code and then compile.


#include <stdio.h>

extern "C"
{
__declspec(dllexport) void DisplayMessageFromDLL()
{
              printf ("Hi From the C DLL!\n");
}

__declspec(dllexport) int DisplayValueAndReturn(int i)
{
        printf("Value %i\n", i);
        return i+2;
}
}



The extern "C" means that the references within the code are going to be available externally and marco __declsepc(dllexport) is for the MS compile to inform that functions are to be available within an dll file.

To create an c# project to communicate with the above dll

1. New project -> c# -> empty project
2. Enter project name (e.g. hellodlltest)
3. Right click on the project name ( in the solution explorer) add-> new item
select class and enter a filename
4. Copy and paste the code and then compile. (you may need to change the Dllimport to the dll file name that has been created from the c dll project)


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

namespace hellodlltest
{
class hellodllC
{
[DllImport("hellocdll.dll")]
public static extern void DisplayMessageFromDLL();

[DllImport("hellocdll.dll")]
public static extern int DisplayValueAndReturn(int i);

static void Main ()
        {
               Console.WriteLine ("C# program 'talking' to an C DLL");
DisplayMessageFromDLL();
Console.WriteLine(DisplayValueAndReturn(3).ToString());
Console.ReadLine()
        }
}
}


5. Copy the dll file from the debug directory of the c++ created dll project and place into the created bin/debug directory for this c# project
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search