You are on page 1of 10

Microsoft Visual Studio C++ & Interfacing Matlab with C/C++, Java and Perl

List of topics 1. Introduction to Visual C++ 6.0 development environment a. Static vs. Dynamic linked libraries Advantages of DLLs b. Creation of these libraries c. Usage of these libraries d. Example: Monte-Carlo method to price a plain vanilla option 2. Interfacing Matlab a. C/C++ b. Java c. Perl

Introduction to Visual C++ 6.0 Microsoft Visual C++ is part of Microsofts software development environment: Visual Studio. It is an integrated development tool used to create and build complex C++ systems with an editor, compiler and a debugger among other things. One can think of it as a development tool similar to NetBeans for Java. In this quick introduction we will look at how to create a simple console project using Visual Studio. This should help the reader to get started to create more interesting project types such as a static library and a dynamic-linked library described in the next section. Here, we will try to price a vanilla call option using a simple Monte-Carlo simulation method. Step 1: Open Microsoft Visual C++ 6.0 and go to File->New. You will see:

You will see a list of project types, of which we would be primarily interested in Win32 Console Application, Win32 Dynamic Link Library and Win32 Static Library. Console Application is the traditional command line program that we all know. Step 2: Select Win32 Console Application, Select a location directory and give a name to the project, for example SimpleMonteCarlo. Click Ok and then Finish on your next screen. You will see a screen similar to:

Step 3: Go to File->New again and select C++ Source File and give a name, say MonteCarloCall and click Ok. Step 4: Switch to FileView tab on your left pane and you will notice that a new C++ file is created. Step 5: Enter the below C++ code and save the file. #include <iostream> #include <cmath> #include <cstdlib> using namespace std; double getNormal() { double value = 0; for(int i=0; i< 10; i++) { value += rand()/static_cast<double>(RAND_MAX); } value -= 5.0; return value; }

double monteCarlo(double strike, double expiry, double current, double r, double sigma, long paths) { double discountedStock = current*exp(r*expiry - 0.5*(sigma*sigma*expiry)); double simulatedStock; double totalPayoff = 0; for(int i=0; i<paths; i++) { double rv = getNormal(); simulatedStock = discountedStock*exp(sqrt(sigma*sigma*expiry)*rv); double payoff = simulatedStock - strike; payoff = payoff > 0 ? payoff : 0.00; totalPayoff += payoff; } double mean = totalPayoff/paths; return (mean*exp(-r*expiry)); } int main() { double price = monteCarlo(70, 0.6, 60, 0.04, 0.30, 100); cout << "Price : " << price << "\n"; return 0; } Step 6: Build the project by right-clicking on the project name on the left pane and selecting build. Step 7: If no compilation errors, execute the program by pressing Ctrl+F5 How to create a simple Dynamic Linked Library (DLL) using VC++? While there are different ways to create dlls, we discuss a method called Implicit linking here. Step 1: New->Project->DLL Step 2: In the cpp file : // #define DLLEXPORT __declspec(dllexport) // Step 3: Declare the methods/functions that you want to export from your dll as DLLEXPORT Ex: DLLEXPORT int multiply(int val1, int val2) { } Step 4: Build the dll. You will see two files: a .dll and a .lib file in your debug directory We are done building a dll now. Let us make an application that uses this dll

Step 1: New->Project->Console Application Step 2: Have a new header file and write the following: // #define DLLIMPORT __declspec(dllimport) // DLLIMPORT int multiple(int, int); Step 3: Go to Project->Settings->Link Tab and include the name of the .lib file of the dll. Step 4: Place the .lib file under the root project directory and the .dll file under the debug directory Step 5: Use the function multiply() just like the way you use any function within you console applications C++ file. Advantages of Dynamic Link Libraries (DLLs) When you statically link a program, the resulting executable file must contain all the data and code that the program may ever need. Consequently, it can become ridiculously large. In addition, changing or extending a program's behavior entails recompilation and relinking. Customers must therefore close the application before they install a new version of the executable whenever you supply an update. Dynamic linking offers several advantages over static linking: code sharing, automatic updates, and security. With dynamic linking, programs can share identical code instead of owning individual copies of the same library. However, there are disadvantages with DLLs often associated with the fact that DLLs are shared by different applications.

Interfacing C/C++ and Matlab


As we know, Matlab provides various ready-made mathematical and numerical functionalities as functions. The ability to use these functions from other programming applications such as C++ is crucial. This would help C++ programmers avoid implementing tedious mathematical functionalities. Let us discuss three ways a C++ program can interact with Matlab: a. Sending data from C++ to Matlab workspace, b. Calling some Matlab functions from a C++ program and getting back the results and c. create dynamic link libraries (dlls) out of Matlab .m files. Matlab facilities this kind of interaction with C/C++ programs through its Engine Library and Compiler. In order to interface with Matlab, a C/C++ program must utilize functions declared in a Matlab provided header file called engine.h. To use this header file and its associated library, one must include the directory that contains this header file and also add all the associated libraries (libmx.lib, libmex.lib, libeng.lib). You can find these libraries in <Matlab Installed Directory>/extern/lib/win32/Microsoft/msvc60 if one is using Visual C++ and the header file in <Matlab Installed Directory>/extern/include. The header file can be referenced in Visual C++ by going to Tools->Options->Directories and adding the above directory under Include Files selection. Libraries can be referenced by adding the appropriate directory under Library Files selection. Sending data to Matlab/Calling some Matlab function: #include<stdio.h> #include<stdlib.h> #include"engine.h" #include<string.h> void main() { Engine *ep; ep = engOpen(NULL); mxArray *mp, *ans; double *ar, *detl; int i,j; double data_c[10] = {3,5,1,5,5,2,0,2,10,6}; mp = mxCreateDoubleMatrix(3,3, mxREAL); memcpy((char *) mxGetPr(mp), (char *) data_c, 10*sizeof(double)); engPutVariable(ep, "data", mp); engEvalString(ep,"ans = det(data);"); ans = engGetVariable(ep,"ans"); detl = mxGetPr(ans); fgetc(stdin); printf("%d",detreal);

//engClose(ep); } Create dlls out of Matlab function Lets have a function called getIV(price, strike, rate, time, value) to calculate the implied volatility of a stock from its option prices using the Black-Scholes formula. function im=getIV(price, strike, rate, time, value) im = blsimpv(100, 95, 0.075, 0.25, 10, 0.5); We can create C++ code/dll out of this function by using this command from Matlab: mcc -W cpplib:bs getIV.m

Interfacing Java and Matlab


Calling Matlab from Java programs Matlab has a suite of jar files to interface and facilitate Java programs to use Matlabs functions. In order to use Matlab, a Java program must first include Matlabs jmi.jar in its CLASSPATH. This jar file can be found in <Matlab Installed Directory>/java/jar directory for Matlab 7.0. Once the jar file is in Javas CLASSPATH, your Java program must include com.mathworks.jmi.*. This will give access to the Matlab and MatlabPath classes, which are the two prime classes to interface with Matlab. Next step would be to create a connection with the current Matlab session by creating an instance of Matlab class: myMatlab = new Matlab() Using this instance, any function of Matlab can be called by using its method eval: myMatlab.eval(impliedVolatility + = blsimpv( + price + ,+strike+,+rate+,+time+,+value+)); This statement will invoke the blsimpv function of Matlab to calculate Implied Volatility of a stock from its option prices. Using JDK from Matlab The first step in using Java classes from Matlab environment is to set the environment variable MATLAB_JAVA to JDK/JVM path. There are no restrictions in terms of the types of Java classes that can be used from Matlab - so, one can call Java built-in classes, third-party classes or user-defined classes from Matlab. Matlab loads Java class definitions from files that are on the Java class path, which is a set of paths that Matlab loads classes from at the start of a session. Matlab, when encountered with a Java class, would search the classpath for the definition of the class. There are two types of classpaths in Matlab: Static and Dynamic. Classes from static path are loaded at the beginning of a session, while classes from dynamic classpath can be loaded/modified any time. Matlab always searches static path before searching dynamic path. As a rule of thumb, include classes that would not change into static path and classes that you expect to change into dynamic path. Matlabs java classpaths can be viewed or modified using the command javaclasspath. So, in order to make all your Java classes available to

Matlab, just put all the compiled classes into a directory say: C:\java\classes and include this location into Matlab classpath using javaaddpath command: Javaaddpath C:\java\classes Making packages or individual classes available to Matlab is similar. Once the classpaths are correctly, you are set to use Java classes from within Matlab code: Arry = java.util.ArrayList(); // Create an ArrayList Arry.add(10); // Add an element 10.0 Arry.size(); // gets the size of the arraylist Option = my.package.BinomialOption(strike, maturity, rate, vol, current); Price = Option.getPrice(); ImpliedVol = my.package.BlackScholes(price, strike, maturity, rate);

Interfacing Perl and Matlab


Calling Perl from Matlab is pretty simple: use the Matlabs perl function: retCode = perl(searchStr.pl, StringToSearch); Invoking Matlab functions from Perl is a little more work. One can use either Win32::OLE or Win32::DDE perl modules to interface with Matlab. Infact, one needs Microsoft Windows to invoke Matlab functions in Perl scripts. Microsoft Component Object Model (COM) enables software components to communicate in windows OS. Using Win32::OLE use Win32::OLE; use Win32::OLE::Variant; use Win32::DDE::Client; eval {$ml = Win32::OLE->GetActiveObject('Matlab.Application')}; die "MATLAB not installed" if $@; unless (defined $ml) { $ml = Win32::OLE->new('Matlab.Application') or die "Oops, cannot start MATLAB"; } $ml->Execute('magicArray = magic(4)'); $mReal = Variant(VT_ARRAY|VT_R8|VT_BYREF,4,4); $mImag = Variant(VT_ARRAY|VT_R8|VT_BYREF,4,4); print "\n>> GetFullMatrix('magicArray', 'base', ",'$mReal, $mImag',")\n"; $ml->GetFullMatrix('im', 'base', $mReal, $mImag); for ($i = 0; $i < 4; $i++) { printf "%3d %3d %3d %3d\n", $mReal->Get($i,0), $mReal->Get($i,1), $mReal->Get($i,2), $mReal->Get($i,3); }

undef $ml; Using Win32::DDE use Win32::DDE::Client; $Client = new Win32::DDE::Client ('Matlab', 'Engine'); die "Unable to start Matlab if $Client->Error; $Client->Execute ('r=rand(4)') || die "failed"; $Client->Execute('im = blsimpv(100, 95, 0.075, 0.25, 10, 0.5)') || die failed; defined ($resp = $Client->Request ('im')) || die " failed"; print "Implied Volatility: $resp\n"; $Client->Disconnect;

References 1. DLLs - http://msdn2.microsoft.com/en-us/library/1ez7dh12.aspx 2. www.mathworks.com - Matlab

You might also like