【问题标题】:Get struct* from out parameter in Chibi Scheme FFI bindings从 Chibi Scheme FFI 绑定中的 out 参数获取 struct*
【发布时间】:2019-04-04 19:13:46
【问题描述】:

你能从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】:

    还是不知道能不能直接做。

    但我能够通过在 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在这个版本中不需要处理任何双重间接(**)。对于 Scheme,C 代码将双间接转换为单间接,因此一切正常。

    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 绑定中复制了该技术,他们面临类似的问题,必须从输出参数中获取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)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多