且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从字符串而不是文件中解析

更新时间:2022-05-19 04:36:10

我最近亲自解决了这个问题.关于该主题的flex文档还有一些不足之处.

I fought through this problem myself very recently. The flex documentation on the subject leaves a bit to be desired.

我马上发现有两件事可能会绊倒你.首先,请注意,您的字符串需要双NULL终止.也就是说,您需要获取一个以NULL终止的常规字符串,并在其末尾添加另一个NULL终止符.这个事实被隐藏在flex文档中,我花了一段时间才找到它.

I see two things right off the bat that might be tripping you up. First, note that your string needs to be double NULL terminated. That is, you need to take a regular, NULL terminated string and add ANOTHER NULL terminator at the end of it. That fact is buried in the flex documentation, and it took me a while to find as well.

第二,您取消了对"yy_switch_to_buffer"的调用.从文档中也不清楚这一点.如果将代码更改为类似的代码,它应该可以工作.

Second, you've left off a call to "yy_switch_to_buffer". This is also not particularly clear from the documentation. If you change your code to something like this, it should work.

// add the second NULL terminator
int len = strlen(my_string);
char *temp = new char[ len + 2 ];
strcpy( temp, my_string );
temp[ len + 1 ] = 0; // The first NULL terminator is added by strcpy

YY_BUFFER_STATE my_string_buffer = yy_scan_string(temp); 
yy_switch_to_buffer( my_string_buffer ); // switch flex to the buffer we just created
yyparse(); 
yy_delete_buffer(my_string_buffer );