in reply to Using c executable in Perl Script

The easiest way to access arrays and hashes when you are using Inline C or XS is to pass by reference and use the access macros to get at the values. Here is a trivial example to get you started.

use Inline 'C'; print multiply( [ 1,2,3,4 ] ); __END__ __C__ double multiply( SV * terms ) { I32 numterms = 0; int i; double result; /* Make sure we have an array ref with values */ if ((!SvROK(terms)) || (SvTYPE(SvRV(terms)) != SVt_PVAV) || ((numterms = av_len((AV *)SvRV(terms))) < 0)) { return 0; } /* Set result to first value in array */ result = SvNV(* av_fetch((AV *)SvRV(terms), 0, 0)); for (i = 1; i <= numterms; i++) { result *= SvNV(* av_fetch((AV *)SvRV(terms), i, 0)); } return result; }

cheers

tachyon

Replies are listed 'Best First'.
Re^2: Using c executable in Perl Script
by sgc (Initiate) on Sep 23, 2004 at 11:56 UTC
    Thank you Tachyon and to everyone who helped to shed some light on my question about C embedded into Perl. I was not aware of the tools available for working with C code, and you have all taught me some good things. I have to admit , I am probably a bit of an oddballish programmer. I start my apps with a picture in mind , and procede to develop a tool in somewhat bruteforce fashion, which in the end does what's required of it, looks and feels good on the outside. I know Perl better now than any other programming language and have developed some powerful tools using Perl/Tk. I've read "C" and understand the fundamentals of the language but have not programmed extensively with it. I used to write code using Unix C-Shell & nawk but am trying to replace all that with Perl now. In the beginning I wondered just how much can one do with Perl/Tk. Initially , it seemed to me that it would be a limited tool in terms of creating GUI's and interacting with various data , but I have been able to "craft" the pictures in my mind into code quite nicely over time.... What are Perl's limits ? Are there things one can do using C / C++ say that could not be done using Perl ? Cheers, sgc

      You can do almost anything in Perl but some things work better in C. Operating systems and device drivers are two examples. Encryption algorithms are an example where the Perl C XS interface is useful. The main code is C with a Perl wrapper. While you can implement almost any algorithm in Perl, it often makes more sense to wrap well tested, and freely available, C library code. That way you get easy access from Perl and don't have to reininvent the wheel.

      cheers

      tachyon