从Chibi Scheme FFI绑定中的out参数获取struct *

问题描述 投票:0回答:1

你能从Chibi Scheme的C函数的out参数中得到一个struct *吗?

我试图从这个C函数得到一个struct archive_entry *

int archive_read_next_header(
    struct archive *archive,
    struct archive_entry **out_entry);

在C中,我会这样做:

struct archive_entry *entry;
archive_read_next_header(archive, &entry);

我的赤壁FFI代码是:

(define-c-struct archive)

(define-c-struct archive_entry)

(define-c int
          archive-read-next-header
          (archive (result reference archive_entry)))

但它没有生成正确的C代码来获得archive_entry。我认为reference是错误的使用方法。我也试过pointer但它也没用。

ffi chibi-scheme
1个回答
0
投票

我还是不知道是否可以直接完成。

但是我能够通过在C中编写自定义thunk函数来解决这个问题:

(c-declare "
struct archive_entry *my_archive_read(struct archive *a, int *out_errcode) {
    struct archive_entry *entry;
    int errcode;

    *out_errcode = errcode = archive_read_next_header(a, &entry);
    return (errcode == ARCHIVE_OK) ? entry : NULL;
}")

(define-c archive_entry my-archive-read (archive (result int)))

所以关键是Scheme在这个版本中不需要处理任何双间接(**)。 C代码将双间接转换为Scheme的单个间接,因此它可以解决所有问题。

Scheme程序的示例用法:

(let ((archive (my-archive-open filename)))
  (disp "archive" archive)
  (let* ((return-values (my-archive-read archive))
         (entry (car return-values))
         (errcode (cadr return-values)))
    (display entry)
    (newline)))

我从chibi-sqlite3绑定中复制了这个技术,他们面临着一个类似的问题,必须从out参数中获取sqlite3_stmt *

(c-declare
 "sqlite3_stmt* sqlite3_prepare_return(sqlite3* db, const char* sql, const int len) {
    sqlite3_stmt* stmt;
    char** err;
    return sqlite3_prepare_v2(db, sql, len, &stmt, NULL) != SQLITE_OK ? NULL : stmt;
  }
")

(define-c sqlite3_stmt (sqlite3-prepare "sqlite3_prepare_return") (sqlite3 string (value (string-length arg1) int)))
© www.soinside.com 2019 - 2024. All rights reserved.