-
Notifications
You must be signed in to change notification settings - Fork 5
Embedding C
Dibyendu Majumdar edited this page Aug 29, 2021
·
21 revisions
Since C is the intermediate language used when generating machine code, we can allow a subset of C as an embedded high performance language.
It does not need to be full blown C as that would be too risky. Instead the goal should be to allow C to write snippets of high performance code.
Following features will not be provided:
- Preprocessor
- Ability to call functions or allocate memory
- The interaction between Ravi and C will be limited to userdata types and primitive types / primitive arrays and strings. No access to Lua tables.
- No assignments to Ravi primitive types in C code (this may be added as a feature later on)
A new keyword C
will be added. It will take a string argument.
C [[
typedef struct {
int i;
} MyStruct;
]]
local i: integer = 1
local j: integer = 2
C [[
long long k = i+j; // Okay as primitive types
]]
When accessing userdata, string or primitive integer types, following implicit types will be used:
// For userdata and string types
typedef struct {
char *ptr;
size_t len;
} Ravi_StringOrUserData;
// For integer[]
typedef struct {
lua_Integer *data;
unsigned int length;
} Ravi_IntegerArray;
// For number[]
typedef struct {
lua_Number *data;
unsigned int length;
} Ravi_NumberArray;
Userdata, string or primitive arrays declared in Ravi code will be accessed in the C snippet as follows:
local narray: number[] = table.numarray(100)
local udata: SomeType = getudata()
C [[
Ravi_NumberArray *numarray = narray;
Ravi_StringOrUserData *udataptr = udata;
// C code can cast the udataptr->ptr to appropriate type
MyStruct *mystruct = (MyStruct *)udataptr->ptr;
// do something with mystruct
]]