March 17, 2011

Unmanaged C++ in C#

Questions
- Using Unmanaged C++ Dynamic Library (DLL) in .NET Applications
- Using DllImport for read a unmanaged dll
- How to Create DLL in Visual Studio 2008 in Visual C++ for Using in C#
- Call an Unmanaged DLL from .Net Windows Application
- Call an Unmanaged Visual C++ code from Managed Code like C# or other .NET

Solution
I have received a request from my friend, He wanted to have a solution with an unmanaged library (DLL) as core and a windows form application in C# as an interface. You can find a very simple solution with 2 languages, here.

- Microsoft Visual C++ 2010 (Unmanaged, Dll)
- Microsoft Visual C# 2010 (Managed, Windows Form)

ClassLibrary.h
// ClassLibrary.h
#define DllExport _declspec(dllexport)
extern "C" DllExport int Sum(int, int);
extern "C" DllExport wchar_t getChar(void);
extern "C" DllExport wchar_t* getString(void);

#pragma once
int Sum(int, int);
wchar_t getChar(void);
wchar_t* getString(void);

ClassLibrary.cpp
#include "stdafx.h"
#include "ClassLibrary.h"

int Sum(int a, int b){return a + b;}
wchar_t getChar(){return L'ن';}
wchar_t* getString(){return L"امیرمهدی خادم آستانه";}

part of Form1.cs
[DllImport("c:\\ClassLibrary.dll", CharSet = CharSet.Unicode)]
[return : MarshalAs(UnmanagedType.I4)]
public static extern Int32 Sum(Int32 a, Int32 b);

[DllImport("c:\\ClassLibrary.dll", CharSet = CharSet.Unicode)]
public static extern char getChar();

[DllImport("c:\\ClassLibrary.dll", CharSet = CharSet.Unicode)]
public static extern String getString();

Download
[1] Unmanaged C++ in C# Solution (both of VC and C# projects) download

3 comments:

spy_lockout said...

Thank you finnaly a normal way to link c# with cpp.
I also have another question is it possible to actually insert a class from cpp into c#?

Of course in theory it should be possible but I couldn't implement it yet, any hints maybe?

spy_lockout

Josh said...

One of the best examples I've seen of clean Interop. Thanks for sharing!

Acton Montgomery said...

In Managed Code, The MSIL value is confirmed for kind protection at JIT gather time. This is a significant plus from a security viewpoint because the confirmation process can avoid bad suggestion adjustment, confirm kind alterations, check range range, and so on.