My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
Exporting  
Exporting C++ variables, functions and methods
Featured, Phase-Design
Updated Feb 4, 2010 by faw...@gmail.com

Exporting using libperl++

libperl++ can export all kind of C++ types. First of all there are primitives such as int and std::string. These can be exported using

interpreter universe;
std::string status;
universe.add("Module::status", status);

Now the variable in C++-space (status) will be synchronized to the one in Perl-space (Module::status). Simple and effective.

Next there are functions. These aren't much harder

extern double atan2(double, double);
universe.add("atan2", atan2);

Again, it just does what you probably expect it to do. A special case is when the function takes a single array argument

void do_something(Array list) {...}

The Array argument is 'slurpy': it takes all arguments. Another interesting aspect of this is that just like with @_ the elements can be written to if they were lvalues, so saying something like this

void do_something(Array list) {
    list[0] += 2;
}

Is entirely valid and does what you want it to do.

Lastly there are classes.

Class<foo> class_foo = universe.get_class("Foo");
class_foo.add(init<int>());
class_foo.add("bar", &foo::bar);

OK, that may need an explanation.

The first line makes the object wrapping the C++ class foo, it' Perl name is Foo. The second line maps a constructor to the class. The constructor takes a single argument, an integer. Currently overloading is not directly supported. The third line exports the member bar. Assuming it was a member function (AKA method) it can be used like this:

my $var = Foo->new;
$var->bar("whatever");

and it will do what you want it to do.

If it was a member variable, it will be usable from perl like this:

$var->bar              # Get value
$var->bar("new value") # Set value

Sign in to add a comment
Powered by Google Project Hosting