gpt4 book ai didi

common-lisp - cffi 函数调用挂起

转载 作者:行者123 更新时间:2023-12-04 02:59:58 25 4
gpt4 key购买 nike

我想使用 stat(2)来自 Common Lisp。

我已经定义了 stat 函数使用的结构:

(cffi:defctype mode_t :unsigned-int)
(cffi:defctype ino_t :unsigned-int)
(cffi:defctype dev_t :int)
(cffi:defctype nlink_t :int)
(cffi:defctype uid_t :unsigned-int)
(cffi:defctype gid_t :unsigned-int)
(cffi:defctype off_t :int)
(cffi:defctype time_t :long)
(cffi:defctype blksize_t :unsigned-int)
(cffi:defctype blkcnt_t :int)

(cffi:defcstruct stat
(st_dev dev_t)
(st_ino ino_t)
(st_mode mode_t)
(st_nlink nlink_t)
(st_uid uid_t)
(st_gid gid_t)
(st_rdev dev_t)
(st_size off_t)
(st_atime time_t)
(st_mtime time_t)
(st_ctime time_t)
(st_blksize blksize_t)
(st_blocks blkcnt_t))

以及函数本身:

(cffi:defcfun "stat" :int
(path :string)
(buf (:pointer (:struct stat))))

我试着像这样简单地调用它:

(cffi:with-foreign-object (buf '(:pointer (:struct stat)))
(stat "/home/florian/tmp/msg.txt" buf)
(cffi:with-foreign-slots ((st_mode) buf (:struct stat))
st_mode))

Slime 只是挂起。没有错误,REPL 输入没有返回。

最佳答案

如果您查看您的 *inferior-lisp* 缓冲区,您会发现 SBCL 由于一些严重的内存损坏而进入其低级调试器。

struct stat 的具体布局在很大程度上取决于您的架构。在我的 64 位 Ubuntu 14.04 上,以下内容似乎有 144 个字节的长度,而您的定义只有 52 个字节长 - 难怪尝试写入它会导致内存损坏。

尝试为操作系统可以自由定义的结构编写 defcstruct 形式可能是个坏主意。该代码可能会在您的计算机上运行,​​但可能不会在其他人的系统上运行,如果他们使用不同的操作系统或处理器架构 - 但如果您真的需要让它仅在您的系统上运行,最简单的方法可能是编写一个简短的 C 程序,在屏幕上转储所有字段的大小和偏移量,然后从那里构建。

如果您需要编写在多个不同系统上运行并使用 stat 的代码,一个不错的选择是自己用 C 编写一个简单的代理模块,具有定义良好的常量接口(interface),代表您调用 stat。这是我在多个场合使用过的方法,在 C 端保证外来内容的安全,并且只通过 FFI 传递真正需要的数据。

对于更稳健的 CFFI 定义,还有 SWIG .

关于common-lisp - cffi 函数调用挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28999781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com