【问题标题】:Common Lisp & CFFI: modifying a global variableCommon Lisp & CFFI:修改全局变量
【发布时间】:2016-09-29 11:02:32
【问题描述】:

我的目标是修改一个 C 全局变量。

假设我有以下 C 头文件:

/* test.h */
int global_variable;

和 C 源文件:

/* test.c */
#include "stdio.h"
#include "test.h"

extern int global_variable;
void test(void) {
    FILE *fp;
    fp = fopen("output.txt", "w");
    fprintf(fp, "Global variable: %d\n", global_variable);
}

global_variable 正确出现在由生成的共享库中

gcc -c -fPIC test.c
gcc -shared -o libtest.so test.o

我的 lisp 界面如下所示:

(ql:quickload :cffi)

(cffi:define-foreign-library libtest
    (:unix (:default "./libtest"))
  (t (:default "./libtest")))

(cffi:use-foreign-library libtest)

(cffi:defcvar ("global_variable" *global-variable*) :int)

(cffi:defcfun "test" :void )

我可以毫无错误地调用测试,但我无法修改 global_variable

(setf *global-variable* 42)

我收到一个警告未定义变量,然后定义(我假设)一个新变量。

那么问题是如何修改common lisp(sbcl)中的global_variable?

提前谢谢你!

【问题讨论】:

  • 我可以写一个 C 函数,例如void set_g(int g) {global_variable = g;},设置global_variable,然后用common lisp为set_g写一个接口。但我认为一定有另一种方式。
  • 在我将缺少的 fclose(fp); 添加到 C 函数后,它似乎对我有用。
  • 非常感谢!
  • 我不知道我应该问一个新问题,还是在这里问。假设我有一个结构体的全局变量: struct block { float x;整数a,b,c; };它在 lisp 中定义为: (cffi:defcstruct block (x :float) (a :int) (b :int) (c :int)) 之后我该如何继续修改它?

标签: common-lisp cffi


【解决方案1】:

对于你的结构,这样的东西应该可以工作:

(cffi:with-foreign-object (ptr 'block)
        ;; setf the slots
        (setf (cffi:foreign-slot-value ptr 'block 'a) 12) ...etc.

【讨论】:

    猜你喜欢
    • 2022-10-01
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多