2016-09-29 65 views
1

我的目標是修改C全局變量。Common Lisp&CFFI:修改全局變量

假設我有以下的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) 

我可以調用的測試,並沒有錯誤,但我不能

(setf *global-variable* 42) 

修改global_variable我得到一個警告不確定的變量,然後定義了(我認爲)的新變量。

所以問題是如何修改common_variable中的通用lisp(sbcl)?

預先感謝您!

+0

我可以寫一個C函數,例如void set_g(int g){global_variable = g;},設置global_variable,然後在common_lisp中爲set_g編寫一個接口。但我認爲必須有另一種方式。 – Dimitris

+1

在我向C函數添加缺少'fclose(fp);'後,它似乎對我有用。 – jkiiski

+0

非常感謝你! – Dimitris

回答

0

對於你的結構,這樣的事情應該工作:

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