如何在 C 代码中构建 Perl 哈希?
我希望在 Perl 中嵌入 C 代码。在这段 C 代码中,我想将一个大文件读入内存,进行一些更改并构建一个散列(自定义散列)。我希望可以从我的 Perl 代码访问这个哈希值。是否可以?我怎样才能达到目标?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了将 c 嵌入到 perl 中,您需要 XS。有关详细信息,请参阅
perlxs
和perlxstut
。至于从 C 构建 perl 数据结构,您必须使用
perlapi
处理哈希值。关于 XS 的许多文档已经解释了其中的各个部分。您要查找的重要部分是newHV
和hv_store
。这是一个类似于您可能想要做的事情的小(且完全未经测试)示例:
这是一个名为
some_func
的 XS 子例程,它将构建一个散列并将其引用返回到 perl 空间:For embedding c in perl, you're looking for XS. Extensive documentation on that can be found in
perlxs
andperlxstut
.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 arenewHV
andhv_store
.Here's a tiny (and completely untested) example of something similar to what you might want to do:
That's an XS subroutine called
some_func
, that'll build a hash and return a reference to it to perl space:接口
把其他的源代码放上来
直接编程语言
Perl 脚本或模块中的“内联”。
代码自动编译为
需要,然后立即加载
从 Perl 访问。
另请阅读为什么我应该使用 Inline 来做到这一点?
interface
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?
您可以使用 SWIG 在 C、Perl 和其他几种语言之间进行交互。
You can use SWIG to interface between C, Perl, and several other languages.