简体   繁体   English

从 php 加载 c 库

[英]Loading c libraries from php

in a recent project I've come really need the lib tre matching library.在最近的一个项目中,我真的需要 lib tre 匹配库。

However the project is in php, and there are no php bindings for the library.但是,该项目在 php 中,并且该库没有 php 绑定。

I've tried to google how to create an interface for c libs, but all I found was the dl function which seams to load only php extensions.我试图用谷歌搜索如何为 c 库创建一个接口,但我发现的只是dl函数,它只能加载 php 扩展。

What am I missing?我错过了什么?

If no " php bindings " exist, it looks like you'll have to develop them ;-)如果不存在“ php 绑定”,则似乎必须开发它们;-)

This is done via a PHP extension -- such as, for example :这是通过PHP 扩展完成的——例如:

  • the mysql extension , that's used to communicate with MySQL, binding the libmysql library (with PHP <= 5.2)mysql扩展,用于与 MySQL 通信,绑定 libmysql 库(使用 PHP <= 5.2)
  • The curl extension , that's a wrapper arround the curl library curl扩展,这是 curl 库的包装器
  • and so many others...还有很多其他人......


If you want to learn more about writing PHP extensions, those links will probably interest you :如果您想了解有关编写 PHP 扩展的更多信息,这些链接可能会让您感兴趣:
(Note that it's not quite an easy task -- but if you are required to... well ^^ ; and some would say it's not that hard ) (请注意,这不是一件很容易的事-但如果你需要...好^^;有些人会说,这并不

And, if you are really interested by the subject, and ready to spend some money on it, you could buy the book Extending and Embedding PHP ( some pages are available as preview on Google Books too) ;而且,如果您真的对这个主题感兴趣,并准备花一些钱,您可以购买扩展和嵌入 PHP一书某些页面也可在 Google 图书上预览 It's considered as the book to read when interested on this subject (In fact, I've bought it some time ago, and, in my opinion, it is indeed an interesting read)对这个话题感兴趣的可以看本书(其实我很久以前就买了,在我看来,确实是一本很有趣的书)

BTW, the author of that book is also the author of the first four articles I linked to ;-)顺便说一句,那本书的作者也是我链接到的前四篇文章的作者;-)

Write an extension that exposes tre to PHP (or find one that already does).编写一个向 PHP 公开 tre 的扩展(或找到一个已经这样做的扩展)。 A good starting point is here .一个好的起点就在这里

Be warned that you won't be able to load your extension on most hosting services.请注意,您将无法在大多数托管服务上加载您的扩展程序。

Since PHP 7.4 the extension FFI (Foreign Function Interface) is bundled, but disabled by default.从 PHP 7.4 开始,捆绑了扩展FFI (外来函数接口),但默认情况下是禁用的。

It should be noted that as of this writing the extension is still considered EXPERIMENTAL, ie its interface may change without notice.应该注意的是,在撰写本文时,该扩展仍被视为实验性的,即其界面可能会更改,恕不另行通知。

Example例子

Calling libc's printf() :调用 libc 的printf()

$ffi = FFI::cdef('int printf(const char *format, ...);', 'libc.so.6');

$ffi->printf('It %s!%s', 'works', PHP_EOL);

Non-CLI SAPIs非 CLI SAPI

By default FFI only works in PHP's CLI SAPI.默认情况下,FFI 仅适用于 PHP 的 CLI SAPI。 For other SAPIs like FPM there are the following options:对于 FPM 等其他 SAPI,有以下选项:

Further reading进一步阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM