chez-scheme FFI的错误,就像C跨平台一样



有一个c文件

#include <stdio.h>
#include <termios.h>

struct termios raw;

int raw_on(void)
{
if (tcgetattr(0, &raw) == -1)
return -1;

raw.c_lflag &= ~ECHO;
raw.c_lflag &= ~ICANON;
raw.c_lflag &= ~ISIG;

// raw.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
// raw.c_oflag &= ~(OPOST);
// raw.c_cflag |= (CS8);
// raw.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
// raw.c_cc[VMIN] = 1;
// raw.c_cc[VTIME] = 0;
return tcsetattr(0, TCSAFLUSH, &raw);
}

当我在chez-scheme中调用它

> (load-shared-object "./emacs.so")
> (foreign-procedure "raw_on"() int)
#<procedure>
> (define raw-on (foreign-procedure "raw_on"() int))
> (raw-on)
Exception: invalid memory reference.  Some debugging context lost
Type (debug) to enter the debugger.

当我在网上搜索时,我发现termios.h是POSIX终端,我的操作系统是Debian。

我可以问一下为什么会出现这个bug吗提前谢谢。

这里的问题是,您绑定到Scheme过程raw-on的C函数raw_on()正在访问全局变量struct termios raw;。问题(我认为)是这些变量不分配位置无关的代码(PIC),除非你声明他们static。由于必须使用-fPIC-shared来构建.so文件,以便在Chez Scheme中执行其中的函数,因此必须将全局变量声明为static,以便在计算load-shared-object时存在这些内存位置。

static struct termios raw; // prepend "static" keyword here
int raw_on(void) { ... }

重建:

cc -fPIC -shared -o ./emacs.so emacs.c

重建emacs.so文件后,再次尝试运行Scheme程序,出现"无效内存引用";失败应该消失。

最新更新