Exporting .NET DLLs with Visual Studio 2005 to be Consumed by Native Applications
Abstract
This article will explain how to create a wrapper for a .NET DLL and import it in MetaTrader 4. I used Visual Studio 2005 and wrote the example .NET DLL in C# and the wrapper in C++. The wrapper is again a DLL, which implements the Stdcall calling convention (MetaTrader 4 supports only this convention but you can produce a DLL with any calling convention as long as .NET supports it). The .NET DLL can be easily written in any other .NET language. The technique described below can be used to export .NET DLLs to be used by any unmanaged applications.
Motivation
When I decided to create an expert advisor for MetaTrader to test a trading strategy, I was frustrated because of many unsuccessful attempts to find out how to create DLLs and import them in the expert advisor. I am coming from a Java background and a year and a half of programming in C#. I have a slight knowledge of C++ and feel like I am crippled when I have to write something in it. Because of that, my first decision was to implement the trading strategy in C#. I spent days trying to figure out how, but my nerves couldn't stand it, so I gave it all up and switched to Visual C++ 6.0. When I realized how quickly I am in writing C++ code, I began having second thoughts and started trying in .NET again. After days of trial and error, I came up with the following step-by-step guide.
Step-by-Step Guide for Creating a Sample DLL
I. Creating the C# DLL
- Create a new C# class library project called CSharpAssembly in a new solution named DotNetDllForMetaTrader4.
- Add the following C# class file to the project: CSharpClass.cs:
- Change the CSharpAssembly project -> Properties -> Build -> Output path field to "..\debug". You do this to dump all the output to one folder.
This step should be completed after adding CppStdcallInerfaceWrapper project to the solution because this will automatically change the solution platform from Any CPU to Mixed Platforms.
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpAssembly
{
public class CSharpClass
{
public static byte[] Hello(byte[] name)
{
string s = ", hello from .NET!";
byte[] helloPart = Encoding.ASCII.GetBytes(s);
byte[] whole =
new byte[name.Length + helloPart.Length];
int i = 0;
foreach (byte b in name)
{
whole[i++] = b;
}
foreach (byte b in helloPart)
{
whole[i++] = b;
}
return whole;
}
}
}
II. Creating the C++ Wrapper, Implementing the Stdcall Calling Convention
- Add to the solution a new C++ Win32 project called CppStdcallInerfaceWrapper with application type DLL.
- Change the CppStdcallInerfaceWrapper.cpp file content to:
- To make the Hello function visible in the CppStdcallInerfaceWrapper.dll through the Stdcall calling convention, add a new Module Definition file called CppStdcallInerfaceWrapper.def in the project source files. This will automatically set the project properties -> Linker -> Input -> Module Definition file.
- To add Hello to the list of exported functions, change the CppStdcallInerfaceWrapper.def content to the following:
- To call the CSharpAssembly.dll, go to project properties -> Configuration Properties -> General and add Common Language Runtime Support.
- To enable the compiler to locate the CSharpAssembly.dll, go to project properties -> C/C++ -> General -> Resolve #using References and add "$(SolutionDir)\debug".
#include "stdafx.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
#ifdef _MANAGED
#pragma managed(pop)
#endif
#using "CSharpAssembly.dll"
using namespace CSharpAssembly;
__declspec(dllexport) char* __stdcall Hello(char* name)
{
int i = 0;
while (*name != '\0')
{
i++;
name++;
}
array<unsigned char>^ nameManArr =
gcnew array<unsigned char>(i);
name -= i;
i = 0;
while (*name != '\0')
{
nameManArr[i] = *name;
name++;
i++;
}
array<unsigned char>^ char8ManArr =
CSharpClass::Hello(nameManArr);
char* char8UnmanArr = new char[char8ManArr->Length + 1];
for (int i = 0; i < char8ManArr->Length; i++)
{
char8UnmanArr[i] = char8ManArr[i];
}
char8UnmanArr[char8ManArr->Length] = '\0';
return char8UnmanArr;
}
LIBRARY "CppStdcallInerfaceWrapper" EXPORTS Hello
III. Creating a Debug Entry Point Project
- Add to the solution a new C# console application project called DebugEntry.
- Add the following C# class file to the project: DebugEntry.cs:
- Change the DebugEntry project -> Properties -> Build -> Output path field to "..\debug". You do this to dump all the output to one folder.
- In solution properties -> Common Properties -> Startup Project, change the single startup project to DebugEntry.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace DebugEntry
{
class DebugEntry
{
[DllImport("CppStdcallInerfaceWrapper.dll",
CharSet = CharSet.Ansi, CallingConvention =
CallingConvention.StdCall)]
public static extern string Hello(string name);
static void Main(string[] args)
{
System.Console.WriteLine(Hello("MyName"));
System.Console.ReadLine();
}
}
}
IV. Setting Project Dependencies and Building the Solution
- Go to solution properties -> Common Properties -> Project Dependencies and set the dependencies as follows:
DebugEntry depends on CppStdcallInterfaceWrapper and CSharpAssembly,
CppStdcallInterfaceWrapper depends on CSharpAssembly. - Build the solution.
V. Testing the DLLs in MetaTrader 4
- Add to the Path environment variable the MetaTrader 4 main directory. Example: "C:\Program Files\MetaTrader 4". You can do it through My Computer -> Properties -> Advanced -> Environment Variables. You do this so MetaTrader 4 can locate your DLLs.
- Copy CSharpAssembly.dll and CppStdcallInerfaceWrapper.dll from "$(SolutionDir)\debug" to MetaTrader's main directory.
The reason you don't put the DLLs in "C:\Program Files\MetaTrader 4\experts\libraries", where external DLLs for MetaTrader usually reside is that when the calling order is MetaTrader 4 Terminal -> CppStdcallInerfaceWrapper.dll -> CSharpAssembly.dll, it will not locate the CSharpAssembly.dll. The Path environment variable can't solve this because the CLR doesn't use it to locate assemblies. That's why I put the DLLs where the MetaTrader terminal executable is. In the Reference section below, there is a link covering the matter on runtime assembly location. - In the MetaTrader platform, create a new expert advisor called DotNetDllTest.
- Before the init() function in DotNetDllTest.mq4, insert the following:
- At the beginning of the init() function, insert:
- Run the DotNetDllTest expert advisor with Allow DLL imports option on.
#import "user32.dll"
int MessageBoxA(int hWnd ,string szText,
string szCaption, int nType);
#import "CppStdcallInerfaceWrapper.dll"
string Hello(string name);
MessageBoxA(100, Hello("MyName"), "", 0);
The user32.dll is a DLL that comes with the Windows operating system; you use it just to show a box with the hello message.Explanations about the Step-by-Step Guide
The DebugEntry project is not necessary, but with it you can debug other projects. To create a release version, all the properties setting steps must be replicated. In the Hello function, project CppStdcallInterfaceWrapper, the char8UnmanArr array is unmanaged and you have to deallocate it, using the delete operator, after you are finished using it in MetaTrader. To keep things simple, this is not done in the example above. You can do it by writing another function in the CppStdcallInterfaceWrapper and calling it from MetaTrader.
Another way of passing data to the unmanaged MetaTrader is not by creating an unmanaged copy, but by using the System.InteropeServices.GCHandle to pin the needed managed object while using it in the unmanaged MetaTrader, so the Garbage Collector doesn't move or delete it.
Other thing you sould take care of is the ecoding convention. .NET strings are in Unicode, whereas the calling application can support only ASCII, like with MetaTrader.
Security Issues
Although there are several available ways to protect your .NET DLLs from back engineering, this is not as secure as native byte code. References to other materials about this matter are provided in the next section.
References
- __declspec(dllexport): http://msdn2.microsoft.com/en-us/library/a90k134d(VS.80).aspx
- http://msdn2.microsoft.com/en-us/library/3y1sfaz2(VS.80).aspx
- __stdcall: http://msdn2.microsoft.com/en-us/library/zxk0tw93(VS.80).aspx
- Delete Operator: http://msdn2.microsoft.com/en-us/library/h6227113(VS.80).aspx
- DllImport attribute: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute(VS.80).aspx
- GCHandle: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.gchandle(VS.80).aspx
- How the Runtime Locates Assemblies: http://msdn2.microsoft.com/en-us/library/yx7xezcf(VS.80).aspx
- Module Definition File: http://msdn2.microsoft.com/en-us/library/28d6s79h(VS.80).aspx
- Mql - Metatrader Development Course: http://www.metatrader.info/book/print/34
- Protecting .NET DLLs: http://www.c-sharpcorner.com/UploadFile/mbmehta/ProtectILCode11232005013513AM/ProtectILCode.aspx
- The "#using" Directive: http://msdn2.microsoft.com/en-us/library/yab9swk4(VS.80).aspx

Comments
http://www.nikeairmaxwr.com/ jmmiln
Posted by http://www.nikeairmaxwr.com/ Mandypdc on 03/30/2013 06:14amNot through the clouds shuttle's ability to grow a variety of ways, but this strange man to the inside through the clouds shuttle injected Reiki, With the injection Reiki increase, the clouds shuttle constantly from a magic weapon to Lingbao later with this strange man becomes a Tempo, and later said that this strange man after missing a forged Yuan Ying. Some people say that oakley sunglasses sale already soaring Once upon a time. Zhuo who repair, I'm afraid next life use the Tempo is wishful thinking. But Zhuo who does not need to use the Tempo Zhuo who only need ray ban inside the aura.cheap ray ban sunglasses, And this aura after the injection of legend who did not know that there is much.ray ban wayfarer, Through the clouds to shuttle the material is extremely strange, actually be able to withstand such a big the Aura pressure without crash, do not know who Warren is how to find such material.ray ban wayfarer sizes, But even the best materials, can not be inside the injection so many Reiki without leaking.
Replyhttp://www.oakleysunglassesoutc.com/ pvriry
Posted by http://www.oakleysunglassesoutc.com/ Mandyvys on 03/29/2013 05:46amghd australia,Huge economic benefits, but also much smaller than abuse coppers as the risk of exposure to big money. The court can receive silver and copper coin casting tax Zhili can the currency row entrusted to the bank, its credit and administrative means to support the currency row, get huge profits from The Industrial and Commercial Bank undertake currency row. And powerful opportunity Zhili Governor House to open up the market, the share of the banking and financial sector dominated by foreign banks to recapture. ICBC and not like its ghd straightener banks, as has just opened is necessary to the busy open up the market pull deposits they have already mastered, but just opened a huge wealth by contractors currency line and began to count the money a few hand cramps to the point where .ghd sale, Plus Tan Yankai Guangdong businessmen to repay borrowings through the use of the U.ghd hair straightener,S.cheap ghd, dollar, making ICBC have mastered the huge amount of dollar deposits in the short term, the joint three shipbuilding docks out payments through the operation of the Industrial and Commercial Bank, said in the business the ICBC the money liquidity is very large.
Replywholesale sunglasses
Posted by qgliliImpumpcuo on 03/28/2013 10:56pmhttp://onlineguciisunglass.webs.com - cheap ray ban wayfarer cheap ray ban,,,, http://replicaguccisunglasses.webs.com - replica oakleys cheap ray ban wayfarer http://discountsunglassessale.webs.com - akley discount replica ray ban http://sunglasssaleulow.webs.com - cheap sunglasses wholesale oakley sunglasses http://discountsunglassessale.webs.com - discount ray ban ray ban cheap
Replyfake ray ban sunglasses
Posted by jgliliImpumpzgu on 03/28/2013 08:23pmhttp://cheapsunglassesshop.webs.com - cheap oakley replica oakleys http://sunglasspomoteauthentic.webs.com - ray ban sunglasses cheap cheap ray ban http://discountsunglassesfinewebs.com - discount sunglasses cheap oakleys http://bestsunglassesshop.webs.com - fake oakley sunglasses cheap ray ban wayfarer http://sunglasspomoteauthentic.webs.com - cheap ray ban sunglasses fake oakley sunglasses
ReplyIsabel Marant Sneakers
Posted by Hauddessy on 03/28/2013 10:07am[url=http://future-select.co.uk/fckeditor/isabelmarantsneakers.aspx]isabel marant boot sale[/url] 07 qiu dong make an appearance,,, like mashups, low-key, can reference! Isabel Marant is recent period designers in France, a only one won a colleague of the international manufacture have attention. After graduating from design style in Paris Studio Bercot, Isabel Marant Yorke and Cole in his figure as a colleague to follow. Spring/summer 2008 the latest thing prove in Paris - the Isabel Marant [Isabel Marant is enthusiasm! Morning star facsimile wear increased in sneakers tide zealot to concourse "mixing in the" needful Neutral look at name avenue part, nothing but recollect, Isabel Marant sneakers increased progress in Europe and the Mutual States is a intrinsic verve! Top banana, acclaimed copy wearing! At hand trend label Isabel ma LAN (Isabel Marant) to motivate the stir of the contemporary cyclone, with long skirts, pants, leather pants, etc. Contrary mention with Isabel ma LAN (Isabel Marant), the craze sneaker avenue snap demonstrations, upon sports sandals teeming rocks in inspiration. Isabel ma LAN (Isabel Marant) shoot for good occasionally pushed on this kind of shoes is in shape far, snapping up, at present in many peculiar shopping website have been sold out. Miranda Kerr, louring leather pants with red [url=http://gateway.recruitment-websites.co.uk/fckeditor/isabelmarant.aspx]isabel marant heels[/url], sufficiency of the color and style. Black and silver match colors, Isabel Marant tie-up and stringent jeans, locomotive leather, handsome Outrageous and white match colors Isabel Marant jeans match and the entirety heart Isabel Marant Ebony even with put on clothing + frog represent, is not a unseemly chart Kate potts voss, Isabel Marant sneaker together with the coin country-like chiffon dresses to rub off last, play is a mashup Solid cream + hand-knitted sweater fastens with color Isabel Marant Isabel Marant sneaker,Cambridge package fluorescent color highlight is the aggregate body Lovers out of the street, Isabel Marant makes mother wit at wish Isabel Marant Website is efforts to donation a pass now. Isabel Marant shoes Comely grey color Isabel Marant sneaker Lightning down and pink are quite let a person enchanted. The multicolor distribution model
Replyhttp://nitinsurana.com
Posted by Nitin on 03/22/2013 10:46amFor all who were unable to set the build output - note that you must have set the release output path and hence, right-click on solution, choose Configuration Manager and set Configuration to RELEASE instead of DEBUG.
Replyghd australia waphiq
Posted by Suttondcq on 03/09/2013 06:17amcheap nike air max orvgbtkj cheap nike free run yiiplkkx cheap nike shoes zghyigjd nike air max chcykjhq nike free run vqlhxptr nike shoes online olkwkyyu
Replyghd australia psvarv
Posted by Mandymmd on 03/08/2013 04:41pmcoach outlet wzelrtaz coach usa nceswdwp coach factory outlet skcnayus coach factory rvnjkknf
Replycheap ugg boots mMhr vMvf
Posted by Mandymrf on 03/07/2013 10:59pmghd france hukrqoet ghd lisseur acualcgp GHD Pas Cher urmevpad ghd ijsomhss lisseur ghd pas cher vvklrewj Lisseur GHD knbvpazt
Replyugg boots noowjb http://www.cheapfashionshoesan.com/
Posted by Mandysrf on 02/19/2013 11:24pmghd nz zpqupdus ghd nz sale ojdhzpbx ghd ownwrkmd
ReplyLoading, Please Wait ...