cptr - using plain C Pointers from neko
Description
The cptr library allows neko programs to create and manipulate plain neko strings as if they are C Pointer data. Memory can be allocated (and will be garbage-collected), the memory block can be accessed to get and set values (treating the data as a list float, double, uint, int, ushort, short, char or uchar), or be passed to other libraries supporting cptr semantics.
While cptr should be memory-safe (allocated memory is garbage collected, and accesses are checked for bounds), cptr still provides plenty of possibility to shoot yourself in the foot- so you should know what you are doing when using it. Especially, endianness of the host system is not taken into account- so the data you are referring to with cptr is not neccessarily "portable" across systems. Also, when using cptrs from other neko libraries, you must take care to do proper bounds checking or you will inevitably get segmentation faults.
CPtr is not well-documented. If you want to use it (either from neko or for another neko-C-library), please ask questions. I will add documentation here as it is created. Meanwhile, cptr is mostly simply a requirement for Xinf.
Installation and Test
You can simply install cptr with haxeLib, it supports all NekoPlatforms.
haxelib install cptr
To run the test, move to the cptr/<version>/test subdirectory of your haxelib path and run
# haxe compile.hxml # neko run run.n Class: TestCPtr .............. OK 14 tests, 0 failed, 14 success
If any of the tests fail, please let me know on the [MailingList].
Using cptr data from other C-based NDLLs
As a (very quick) intro, if you are writing another C-based neko library, you can use data that is setup/handled/read with cptr without any special header file or anything. Pass the data as neko strings, and do your bounds checking.
An example that uses a pointer to a list of (minimum) four double-precision floating-point numbers:
static value bind_GL_color4dv( value n_v ) {
double* v;
val_check( n_v, string );
if( val_strlen( n_v ) < sizeof(double)*4 ) val_throw(alloc_string("cptr too small"));
v=(double*)val_string(n_v);
glColor4dv(v); return val_null;
}
DEFINE_PRIM(bind_GL_color4dv,1);
If you want to pass data from your C library to neko, you'll need to use copy_string. Yes, this involves a memcpy (sorry. find a better solution?).
static value get_data() {
double *v = malloc( sizeof(double)*4 );
memset( v, 0, sizeof(double)*4 );
value r = copy_string( (char*)v, sizeof(double)*4 );
return r;
}
DEFINE_PRIM(get_data,0);
