How can I build a Perl hash in C code?
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 c开发者_C百科ode. Is it possible? How can I reach the goal?
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 };
- 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?
You can use SWIG to interface between C, Perl, and several other languages.
精彩评论