I wish to embed a C code in Perl. In this C code I want to read a huge file into memory, make some changes and build a hash (a custom one). I wish to make this hash accessible from my Perl code. Is it possible? How can I reach the goal?
+3
A:
- See Internals and C language interface
- Also have a look at Inline-C for embedded a C code in perl:The Inline module allows you to put source code from other programming languages directly "inline" in a Perl script or module. The code is automatically compiled as needed, and then loaded for immediate access from Perl.
Also read Why should I use Inline to do it?
Nikhil Jain
2010-10-05 08:49:38
Oh please stop recommending Inline as the de-facto standard solution to such things. It's a deployment nightmare. Unless the requirement is specifically "I need to do this on my machine and my machine only", Inline translates to problems down the road.
tsee
2010-10-05 13:00:54
I'll write XS code when I have to, but when I don't have to, Inline::C is awesome.
mobrule
2010-10-05 14:56:55
+9
A:
For embedding c in perl, you're looking for XS. Extensive documentation on that can be found in perlxs
and perlxstut
.
As for building perl data structures from C, you will have to use the parts of the perlapi
that deal with hashes. Much documentation on XS already explains various bits of that. The important parts you're looking for are newHV
and hv_store
.
Here's a tiny (and completely untested) example of something similar to what you might want to do:
SV *
some_func ()
PREINIT:
HV *hash;
CODE:
hash = newHV();
hv_stores(hash, "foo", 3, newSViv(42));
hv_stores(hash, "bar", 3, newSViv(23));
RETVAL = newRV_noinc((SV *)hash);
OUTPUT:
RETVAL
That's an XS subroutine called some_func
, that'll build a hash and return a reference to it to perl space:
my $href = some_func();
# $href = { foo => 42, bar => 23 };
rafl
2010-10-05 08:53:53