1

我的目标是修改 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?

先感谢您!

4

1 回答 1

0

对于您的结构,这样的事情应该可以工作:

(cffi:with-foreign-object (ptr 'block)
        ;; setf the slots
        (setf (cffi:foreign-slot-value ptr 'block 'a) 12) ...etc.
于 2017-07-09T12:06:23.773 回答