dragon19720808 2013-05-13 22:33
浏览 50
已采纳

从PHP打包C结构

I've played around with pack() for longer than I'd like to admit, and accidentally stumbled across data structure alignment. Is there a "good" way to create C structures from within PHP and account for these extra padding bytes?

I know that you can use "x" to inject NULL bytes, but how do you determine where these go and how many to use programmatically?

Along the same lines, which of these methods is better for modeling a char foo[10] array?

$struct = pack('a9x', $string);
// vs.
$struct = pack('a10', substr($string, 0, 9));

I believe they both accomplish the same thing, but I'm not sure of any potential pitfalls.

  • 写回答

1条回答 默认 最新

  • duanshanduo3363 2013-05-13 22:45
    关注

    What you try to do is achievable, but highly dangerous. Let me explain:

    • PHP code is largely independant from the Hardware/OS/C runtime it runs on
    • (Portable) C source code mostly is also
    • The compilation/linking/loading process of a C binary definitly is not (especially if you leave the padding/packing issues to the compiler)

    Now what you try to do in PHP is a partial reimplementation of exactly this compilation/linking/loading process, but without a reliable mechanism to determine to adapt to the environment.

    I recommend one of two IMHO more reliable ways to do this:

    • Write a PHP extension (this is rather easy), that does the structure-dependant stuff for you, including the headers from your C program. If you compile this on the target system (or one with an equal environment) you will not run into the troubles above
    • Chose another, higher level mechanism to communicate: We have successfully used SysV messages for a very similar requirement, but there are plenty of ways to go.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端