Machine code: Difference between revisions

Content added Content deleted
No edit summary
(→‎{{header|Wren}}: Tidied and fixed a potential seg fault in C code.)
Line 1,631: Line 1,631:


However, it is designed for embedding and we can therefore ask the host to do this for us. Here, we use a host program written in C, the language which Wren itself is written in.
However, it is designed for embedding and we can therefore ask the host to do this for us. Here, we use a host program written in C, the language which Wren itself is written in.
<syntaxhighlight lang="ecmascript">/* machine_code.wren */
<syntaxhighlight lang="wren">/* Machine_code.wren */
class C {
class C {
Line 1,653: Line 1,653:
<br>
<br>
We now embed this Wren script in the following C program, compile and run it.
We now embed this Wren script in the following C program, compile and run it.
<syntaxhighlight lang="c">#include <stdlib.h>
<syntaxhighlight lang="c">/* gcc Machine_code.c -o Machine_code -lwren -lm */

#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
Line 1,679: Line 1,681:
void C_runMachineCode(WrenVM* vm) {
void C_runMachineCode(WrenVM* vm) {
/* unpack arguments passed from Wren */
/* unpack arguments passed from Wren */
int *len;
int len;
const char *code = wrenGetSlotBytes(vm, 1, len);
const char *code = wrenGetSlotBytes(vm, 1, &len);
unsigned char a = (unsigned char)wrenGetSlotDouble(vm, 2);
unsigned char a = (unsigned char)wrenGetSlotDouble(vm, 2);
unsigned char b = (unsigned char)wrenGetSlotDouble(vm, 3);
unsigned char b = (unsigned char)wrenGetSlotDouble(vm, 3);


/* obtain result */
/* obtain result */
unsigned char c = rmc_helper(code, a, b, *len);
unsigned char c = rmc_helper(code, a, b, len);
/* return result to Wren */
/* return result to Wren */
Line 1,745: Line 1,747:
WrenVM* vm = wrenNewVM(&config);
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* module = "main";
const char* fileName = "machine_code.wren";
const char* fileName = "Machine_code.wren";
char *script = readFile(fileName);
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
WrenInterpretResult result = wrenInterpret(vm, module, script);