如何将静态 C 目标文件链接到 Perl?
我有一个用 C 编写的函数(在 HelloWorld.c 文件中)。 我想编译它并需要创建一个静态目标文件 HelloWorld.a
最后我需要从 Perl 程序 (HelloWorld.pl) 调用它。
I have a function written in C (Say in HelloWorld.c file).
I want to compile this and need to create a staic object file HelloWorld.a
Finally I need to call this from a Perl program (HelloWorld.pl).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要从 Perl 调用 C,通常会从他的 C 代码编译一个共享库,而不是静态库,然后使用
XSLoader
或DynaLoader
模块将其加载到 Perl 解释器中。为了能够从 Perl 空间调用 C 代码,有很多方法。最常见的一种是编写称为 XSUB 的东西,它具有 perl 端接口,将 perl 调用约定映射到 C 调用约定,并调用 C 函数。这些 XSUB 通常也链接到将加载到 Perl 中的共享库,并用称为 XS 的语言编写,该语言在 perlxs 和 perlxstut。
还有其他方法可以构建该包装层,例如各种 XS 代码生成器以及 SWIG。但您也可以使用
NCI
直接调用 C 函数。 Perl 也有很多这样的东西。P5NCI
是其中一个示例,今年 Google Summer of Code 计划中开发的 ctypes 模块是另一个示例。这里可能应该提到的另一个相关技术是 Inline::C 以及 Inline 系列的其他模块。它们允许您直接在 Perl 中编写其他语言的代码并调用它。在底层,Inline::C 只是构建 XS 代码并将其结果加载到解释器中。
To call from perl to C one usually compiles a shared, not a static, library from his c code, and then loads that into the perl interpreter using the
XSLoader
orDynaLoader
module.To then be able to call the C code from perl space there's many ways. The most common one is writing something called
XSUB
s, which have a perl-side interface, map the perl calling-conventions to C calling-conventions, and call the C functions. Those XSUBs are usually also linked into the shared library that'll be loaded into perl, and written in a language called XS, which is extensively documented in perlxs and perlxstut.There's also other ways to build that wrapper layer, like various XS code generators, as well as SWIG. But you could also call to the C functions directly using an
NCI
. Perl also has many of those. TheP5NCI
is one example of those, the ctypes module developed in this year's Google Summer of Code program is another.Another related technique that should probably be mentioned here is
Inline::C
, and the other modules of the Inline family. They allow you to write code in other languages directly in perl, and call to it. Under the hood Inline::C just builds XS code and loads the result of that into the interpreter.正如@rafl 所说,您应该使用共享库。
如果您必须使用静态库,那么您必须使用内置静态库重建 Perl。您还需要一些 XS 胶水。然而,这太混乱了,你真的真的不想这样做。
As @rafl says, you should use a shared library.
If you must use a static library, then you have to rebuild Perl with the static library built in. You'll need some XS glue too. However, this is messy enough that you really, really don't want to do it.
根据perlxstut:
According to perlxstut: