【问题标题】:Using CFFI in Common Lisp, calling functions returning pointers在 Common Lisp 中使用 CFFI,调用返回指针的函数
【发布时间】:2018-03-08 22:24:35
【问题描述】:

我正在使用 SBCL,并尝试使用 CFFI。我开始按照手册here 进行操作,但我不断发现函数curl_easy_init 是未定义的,所以我决定尝试一个更简单的案例。

一些函数按预期工作,而另一些函数似乎没有定义。这解释如下:

这是我的 C 代码:

#include <stdio.h>
#include <stdlib.h>

/* "Works" except output doesn't appear. Not important for now */
void hello()
{
  printf("Hello World\n");
}

/* Works as expected */
float add(float x1, float x2)
{
  return x1 + x2;
}

/* appears to not be defined in SBCL*/
void* init_this()
{
  return malloc(10);
}

/* Appears to not be defined in SBCL*/
void clean_this(void* ptr)
{
  free(ptr);
}

这个C文件编译为:

gcc -shared -o cffi_test.so -fPIC cffi_test.c

我的 Common Lisp 代码:

(quicklisp:quickload "cffi")

(defpackage :my-cffi
  (:use :common-lisp :cffi))

(in-package :my-cffi)
(export '(hello add init_this clean_this))


(define-foreign-library cffi_test
  (t (:default "~/Work/clisp/cffi_test")))

(use-foreign-library cffi_test)

(defcfun "hello" :void)
(defcfun "add" :float (x1 :float ) (x2 :float))
(defcfun "init_this" :pointer)
(defcfun "clean_this" :void (handle :pointer))

如我所愿:

* (my-cffi:add 3.0 4.0)

7.0

似乎有什么问题:

(my-cffi:init_this)

产生错误:

The function MY-CFFI:INIT_THIS is undefined.
   [Condition of type UNDEFINED-FUNCTION]

...

Backtrace:
  0: (SB-IMPL::RETRY-%COERCE-NAME-TO-FUN MY-CFFI:INIT_THIS NIL)
      Locals:
        SB-IMPL::NAME = MY-CFFI:INIT_THIS
        SB-IMPL::STRICTLY-FUNCTIONP = NIL

clean_this 和上面的链接中出现了同样的错误,按照手册,curl_easy_init 启发了这个实验。

【问题讨论】:

  • CFFI 将外国名称中的下划线翻译成破折号。
  • 谢谢!有效。你想在答案部分发布,以便我接受并关闭它吗?

标签: common-lisp sbcl cffi


【解决方案1】:

以字符串形式提供给CFFI:DEFCFUN 的外来名称将使用通用函数CFFI:TRANSLATE-NAME-FROM-FOREIGN 转换为lispier 名称。默认行为是将下划线更改为连字符:

CL-USER> (cffi:translate-name-from-foreign "mylib_fun_name" *package*)
MYLIB-FUN-NAME

你也可以在函数定义中明确给出一个 lisp 名称:

(defcfun ("mylib_fun_name" fun-name) ...)

【讨论】:

    猜你喜欢
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多