CSC/ECE 517 Fall 2010/ch3 3i IC

From Expertiza_Wiki
Revision as of 03:16, 4 October 2010 by Ipcolema (talk | contribs) (→‎Python)
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

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.

Below is a “Hello, World!” example.

C++ function declaration:

char* greet() {

   return “Hello, World!”;

}

Adding to C++ so it can be exposed to Python:

  1. include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello_ext) {

   using namespace boost::python;
   def(“greet”, greet);

} Python code that calls C++ function: import hello_ext # notice this is the parameter passed to BOOST_PYTHON_MODULE print hello.greet()

>> Hello, World! Class example:

class Person {

private string name;

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

}

string getName()

{

   return name;

} };

Boost.Python C++ Wrapper:

  1. include <boost/python.hpp>

using namespace boost::python;

BOOST_PYTHON_MODULE(person) {� class_<Person>("person")� .def("getName", &Person::getName)� .def("setName", &World::setName)�  ;�}

Python: import person student = person.Person() student.setName(‘John’) student.getName()

>> John

Lua

Mixing Dynamic Code and Java

Perl

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