环/教程/在 C/C++ 程序中嵌入环解释器
外观
< 环
我们可以使用以下函数从 C/C++ 程序中调用环解释器
RingState *ring_state_init();
ring_state_runcode(RingState *pState,const char *cCode);
ring_state_delete(RingState *pState);
想法是使用 ring_state_init() 为环解释器创建新的状态,然后调用 ring_state_runcode() 函数使用相同的状态执行环代码。完成后,我们调用 ring_state_delete() 释放内存。
示例
#include "ring.h"
#include "stdlib.h"
int main(int argc, char *argv[])
{
RingState *pState = ring_state_init();
printf("welcome\n");
ring_state_runcode(pState,"see 'hello world from the ring programming language'+nl");
ring_state_delete(pState);
}
输出
welcome
hello world from the ring programming language
环 API 带有以下函数来创建和删除状态。我们还有函数来创建新变量和获取变量值。
RingState * ring_state_init ( void ) ;
RingState * ring_state_delete ( RingState *pRingState ) ;
void ring_state_runcode ( RingState *pRingState,const char *cStr ) ;
List * ring_state_findvar ( RingState *pRingState,const char *cStr ) ;
List * ring_state_newvar ( RingState *pRingState,const char *cStr ) ;
void ring_state_main ( int argc, char *argv[] ) ;
void ring_state_runfile ( RingState *pRingState,const char *cFileName ) ;
我们可以在同一个程序中创建多个环状态,并且可以创建和修改变量值。
要获取变量列表,我们可以使用 ring_state_findvar() 函数。
要创建新变量,我们可以使用 ring_state_newvar() 函数。
示例
#include "ring.h"
#include "stdlib.h"
int main(int argc, char *argv[])
{
List *pList;
RingState *pState = ring_state_init();
RingState *pState2 = ring_state_init();
printf("welcome\n");
ring_state_runcode(pState,"see 'hello world from the ring programming language'+nl");
printf("Again from C we will call ring code\n");
ring_state_runcode(pState,"for x = 1 to 10 see x + nl next");
ring_state_runcode(pState2,"for x = 1 to 5 see x + nl next");
printf("Now we will display the x variable value from ring code\n");
ring_state_runcode(pState,"see 'x value : ' + x + nl ");
ring_state_runcode(pState2,"see 'x value : ' + x + nl ");
pList = ring_state_findvar(pState,"x");
printf("Printing Ring variable value from C, %.0f\n",
ring_list_getdouble(pList,RING_VAR_VALUE));
printf("now we will set the ring variable value from C\n");
ring_list_setdouble(pList,RING_VAR_VALUE,20);
ring_state_runcode(pState,"see 'x value after update : ' + x + nl ");
pList = ring_state_newvar(pState,"v1");
ring_list_setdouble(pList,RING_VAR_VALUE,10);
pList = ring_state_newvar(pState,"v2");
ring_list_setdouble(pList,RING_VAR_VALUE,20);
ring_state_runcode(pState,"see 'v1 + v2 = ' see v1+v2 see nl");
ring_state_runcode(pState,"see 'end of test' + nl");
ring_state_delete(pState);
ring_state_delete(pState2);
}
输出
welcome
hello world from the ring programming language
Again from C we will call ring code
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
Now we will display the x variable value from ring code
x value : 11
x value : 6
Printing Ring variable value from C, 11
now we will set the ring variable value from C
x value after update : 20
v1 + v2 = 30
end of test