nbind
nbind copied to clipboard
Add wrapper class support.
hi~, suppose a method return a Buffer object, you have to code like this:
c++
void drawToBuffer(int size, nbind::cbFunction& callback) {
nbind::Buffer buf = callback.call<nbind::Buffer>(size);
// ...
buf.commit();
}
#include "nbind/nbind.h"
NBIND_GLOBAL() {
function(drawToBuffer);
}
javascript
let result = drawToBuffer(function(size) {
return Buffer.alloc(size);
})
I suggest two ways of interact with c++ code that will return an object of js buildin types/classes.
- Give a constructor to nbind::Buffer, so you can create an "instance" of that type like std::vector.
nbind::Buffer drawToBuffer(bool useBackground, float rotate) {
nbind::Buffer buf(128);
// ...
buf.commit();
return buf;
}
#include "nbind/nbind.h"
NBIND_GLOBAL() {
function(drawToBuffer);
}
javascript:
let imageBuffer = binding.lib.drawToBuffer(false, 0);
- Add support for js inner types binding. instead of using NBIND_CLASS, give a new micro NBIND_WRAP.
class ImageBuffer {
public:
static nbind::Buffer toJS(ImageBuffer *);
static nbind::Buffer toJS(ImageBuffer); // overwrite
static ImageBuffer *fromJS(nbind::Buffer); // user should release the newly create ImageBuffer*
static ImageBuffer fromJS(nbind::Buffer);// overwrite
static ImageBuffer& fromJS(nbind::Buffer, ImageBuffer& objectToInit);// overwrite
public:
unsigned char* data;
int length;
}
void addWaterPrint(ImageBuffer);
NBIND_GLOBAL() {
function(addWaterPrint);
}
NBIND_WRAP<nbind::Buffer>(ImageBuffer);
javascript:
let buffer = fs.readFileSync(/*...*/);
binding.lib.addWaterPrint(buffer);
another example:
class NetWorkConfig {
public:
static std::string toJS(NetWorkConfig *); // you can join all properties to an string like hostname#port#path
static NetWorkConfig *fromJS(std::string); // split the input string by '#' and you get [hostname,
static NetWorkConfig fromJS(std::string); // overwrite for different argument types.
public:
std::string hostname;
std::string port;
std::string path;
}
bool setupConnection(NetWorkConfig config);
NBIND_WRAP<std::string>(NetWorkConfig);
NBIND_GLOBAL() {
function(setupConnection);
}
javascript:
let serverAddress = 'http://some.domain.name.com#8080#/your/resource/path';
let hasConnected = binding.lib.setupConnection(serverAddress);
if(hasConnected) {
// ...
}
This is extremely useful when working with matirx operation library, there will be a great improvement when you can convert '1,0,0,0,1,0,0,0,1' to an native Matirx33 object