CSC/ECE 517 Fall 2010/ch3 3i IC

From Expertiza_Wiki
Revision as of 04:33, 4 October 2010 by Ipcolema (talk | contribs) (→‎Boost)
Jump to navigation Jump to search

Mixing Static and Dynamic Language Code


Introduction

Many middleware solutions have been developed to combine static and dynamic languages to take advantage of both types of code. Previous wiki chapters have discussed JRuby, a Java implementation Ruby. These solutions allow programmers the productivity luxuries of newer dynamic languages with the speed, low-level functionality, and pre-existing code base of older static languages. Below, we will give even more examples of mixing several widely used dynamic languages with C, C++, and Java.

Mixing Dynamic Code and C/C++

Ruby

Ruby has an inherent relationship with the C language since the current Ruby implementation is written in C. Cplus2Ruby is a gem that allows programmers to call Ruby code within C++ and vice versa. Assuming an installation of Ruby, the Cplus2Ruby can be installed with the following command [2]:

gem install cplus2ruby

Python

Using Boost

Boost allows programmers to seamlessly expose C++ classes and function to Python and vice versa. No special tools are needed (however, a build tool will be referenced later). All that is required are the Boost libraries and a C++ compiler. Boost is designed to allow Python to use C++ code with no internal modification to the C++ code that will be wrapped.

Exposing Functions

Below is a “Hello, World!” example.

C++ function

string greet()
{

return "Hello, World!";

}

Add to C++ so it can be exposed to Python

#include <boost/python.hpp>
BOOST_PYTHON_MODULE(hello_ext)
{

using namespace boost::python;
def("greet", greet);

}

Python code that calls C++

import hello_ext # parameter passed to BOOST_PYTHON_MODULE
print hello.greet()
>> Hello, World!

Exposing Classes

C++ Class Declaration

class Person
{

private string name;


void setName(string name)
{
this->name = name;
}


string getName()
{
return name;
}

};

Boost.Python C++ Wrapper

#include <boost/python.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(person)
{

class_<Person>("person")
.def("getName", &Person::getName)
.def("setName", &Person::setName);

}

Python Code

import person
student = person.Person()
student.setName('John')
student.getName()

>> John

Lua

Mixing Dynamic Code and Java

Perl

Using Inline::Java

Java Code

public class Person {

String name;
public getName()
{
return name;
}
public setName(String newName)
{
this.name = newName;
}

}

References

[1] Steve Vinoski. Ruby Extensions. Internet Computing, IEEE, Vol. 10, Issue 5. 2006. pp. 85-87.

[2] Michael Neumann. Cplus2Ruby - Gluing C++ and Ruby together in an OO manner. http://rubydoc.info/gems/cplus2ruby/1.2.0/frames

[3] Dave Abrahams. Boost.Python. http://www.boost.org/doc/libs/1_44_0/libs/python/doc/index.html

[4] Phil Crow. Bringing Java into Perl. 2003. http://www.perl.com/pub/2003/11/07/java.html