Skip to content

Instantly share code, notes, and snippets.

@hdf
Created February 8, 2016 19:27
Show Gist options
  • Save hdf/2a813c972bf323f3bfc4 to your computer and use it in GitHub Desktop.
Save hdf/2a813c972bf323f3bfc4 to your computer and use it in GitHub Desktop.
node-ffi experiment
// g++ -O3 -pie -shared t1.cpp -o t1.dll
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
extern "C" {
__declspec(dllexport)
void callme(char ***out, char *out2) {
char s[2][3][6] = {{"one", "two", "three"}, {"four", "five", "six"}};
printf("%s\n", s[1][1]);
memcpy(out, s, sizeof(s));
memcpy(out2, s[1][0], sizeof(s[1][0]));
}
}
var ffi = require('ffi'),
ref = require('ref'),
ArrayType = require('ref-array');
var Str = ArrayType('char');
var StringArray = ArrayType(Str);
var StringArrayArray = ArrayType(StringArray);
var dll = ffi.Library('t1.dll', {
'callme': [ 'void' , [ StringArrayArray, ref.refType('string') ] ]
});
//var r = new StringArrayArray([new StringArray([new Str(6), new Str(6), new Str(6)]),
// new StringArray([new Str(6), new Str(6), new Str(6)])]);
var r = new Buffer(6*3*2);
var r2 = ref.alloc(ref.refType('string'), null);
dll.callme.async(r, r2, function (err, res) {
//dll.callme(r, r2);
console.log(r);
console.log(ref.readCString(r, 4*6));
console.log(ref.readCString(r2, 0));
});
// g++ -O3 t1_test.cpp -o t1_test
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef void (CALLBACK* callme)(char***, char*);
int main(int argc, char* argv[]) {
HMODULE handle = LoadLibrary("t1.dll");
printf("handle: %ld\n", handle);
callme dll = (callme)GetProcAddress(handle, "callme");
printf("dll: %ld\n", dll);
char a[2][3][6];
char b[6];
dll((char***)a, b);
printf ("returned: %s %s\n", a[1][1], b);
FreeLibrary(handle);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment