cesanta / v7

Embedded JavaScript engine for C/C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

C program crashes when trying to retrieve one of struct members as object member if below 0

Rabios opened this issue · comments

Hi there!

I'm working on JavaScript bindings for raylib, It's game programming library, Using the amazing v7 JavaScript engine!

Anyway, With structs i'm stuck cause if one of struct values are below 0 (I'm using C structs from JavaScript as function with object prototype)

Here is raylib struct Vector2 for example...

typedef struct Vector2 {
    float x;
    float y;
} Vector2;

And here is how i make object prototype of it!

void js_push_val(struct v7* v7, v7_val_t obj, char* var_name, v7_val_t val) {
	v7_set(v7, obj, var_name, ~0, val);
}

void js_push_key(struct v7* v7, v7_val_t obj, char* var_name, double val) {
	v7_set(v7, obj, var_name, ~0, v7_mk_number(v7, val));
}

enum v7_err js_vec2(struct v7* v7, v7_val_t* res) {
	v7_val_t this = v7_get_this(v7);

	float x = (float) v7_get_double(v7, v7_arg(v7, 0));
	float y = (float) v7_get_double(v7, v7_arg(v7, 1));
	
	js_push_val(v7, this, "x", x);
	js_push_val(v7, this, "y", y);

	*res = this;
	return V7_OK;
}

v7_set(v7, v7_get_global(v7), "Vector2", ~0, v7_mk_function_with_proto(v7, js_vec2, v7_mk_object(v7)));

And here is how i use it from JavaScript

var vec2 = new Vector2(100, 100);

When i want to get Vector2 as argument from JavaScript, Here is how i did it:

Vector2 js_get_vec2(struct v7* v7, unsigned int arg) {
	Vector2 vec2 = (Vector2) {
		v7_get(v7, v7_arg(v7, arg), "x", ~0),
		v7_get(v7, v7_arg(v7, arg), "y", ~0),
	};
	return vec2;
}

And here comes the problem, If x or y retrived from Vector2 using js_get_vec2 below 0, Program crashes for unexpected reason...

And i believe problem comes from v7, If someone willing to fix it for me i would be grateful!

You literally opened this an hour ago. Be patient.

@Rabios it's all good. I hope you get an answer soon 👍

Closing issue as it's fixed via this way:

Vector2 js_get_vec2(struct v7* v7, unsigned int arg) {
	Vector2 vec2 = (Vector2) {
		(float)v7_get_double(v7, v7_get(v7, v7_arg(v7, arg), "x", ~0)),
		(float)v7_get_double(v7, v7_get(v7, v7_arg(v7, arg), "y", ~0)),
	};
	return vec2;
}

void js_return_vec2(struct v7* v7, v7_val_t* res, Vector2 vec2) {
	*res = v7_mk_object(v7);
	v7_set(v7, *res, "x", ~0, v7_mk_number(v7, (float)vec2.x));
	v7_set(v7, *res, "y", ~0, v7_mk_number(v7, (float)vec2.y));
}