Wrap C++ object without going through constructor - c++

I have a C++ object which inherits from node::ObjectWrap. The object itself manages the resource so it accepts it as an argument in a private constructor.
When object is created from Javascript it's quite straightforward:
void New(const v8::FunctionCallbackInfo<v8::Value>& args) {
// ...
auto handleToCustomResource = resolveFromJSArg(args[0]->ToString());
auto object = new MyObjectWrap(handleToCustomResource);
object->Wrap(args.This());
args.GetReturnValue().Set(args.This());
}
However it's not clear how to wrap the object when it originates from C++, here is my recent effort:
public v8::Local<v8::Object> CreateObject(v8::Isolate *isolate, const char *name) {
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::EscapableHandleScope scope(isolate);
auto object = new MyObjectWrap(handleToMyCustomResource);
v8::Local<v8::Object> instance = // eh don't have an instance??
object->Wrap(instance);
return scope.Escape(instance);
}
How to properly create a JS object so I could use it as an instance for my native object?
One of workarounds I found is to basically have two constructors, one public and one private and then inherit one from another. The public one is available in javascript, while the private is solely used to create an instance for wrapping an existing ObjectWrap object.
v8::Local<v8::FunctionTemplate> privTpl = v8::FunctionTemplate::New(isolate, PrivateNew);
v8::Local<v8::FunctionTemplate> pubTpl = v8::FunctionTemplate::New(isolate, New);
// define prototype
pubTpl->Inherit(privTpl);
exports->Set(v8::String::NewFromUtf8(isolate, "MyObject"), tpl->GetFunction());

Related

What is the common context base class used by Java code delegates?

What is the common base class used by Java code delegates so that common code can be used to get/set process variables etc?
For a service-task, the process engine context class is DelegateExecution and typically, to get a process variable, this context, passed as a parameter is used to access process variables.
...
public class CreatePurchaseOrderRequistionDelegate implements JavaDelegate
{
public void execute( DelegateExecution execution ) throws Exception
{
LOGGER.info( getClass().getSimpleName() + ": starting" );
String purchaseOrderRef = (String) execution.getVariable( "purchaseOrderReference" );
...
For a user-task event listener, the context class is DelegateTask.
I want to use the same code to get/set process variables so need a base class that has access to setVariable(), etc
I have looked at the Camunda Manual, Javadocs etc but both classes inherit from a number of other classes and it is difficult to trace the inheritance tree.
It should be: org.camunda.bpm.engine.delegate.VariableScope
So something like:
public static String getVariableS( VariableScope execution, String variableName, String defaultValue ) throws Exception
{
Object obj = execution.getVariable( variableName );
if( obj == null )
{
return defaultValue;
}
return (String) obj;
}
Hope this helps!

Creating a fallback container/resolver DryIoc

Current working on creating a Prism.DryIoc.Forms project to try out DryIoc (first time!).
In Xamarin.Forms there is a native DependencyService and to provide a nice way to migrate towards using Prism I would like to add it as a fallback container in case the requsted service type can't be resolved from the main container.
Current I have created a FallbackContainer and pass the instance of IContainerand overrides the methods for IResolver and delegates the rest of the IContainer calls to the instance passed during creation.
So after the default container is created and configured and then do
Container = CreateContainer();
ConfigureContainer();
Container.Rules.WithFallbackContainer(new DependencyServiceContainer(Container));
Is this the preferred method or is there any way just to attach a default IResolver?
Current implementation
public class FallbackDependencyServiceContainer : IContainer
{
private readonly IContainer container;
public FallbackDependencyServiceContainer(IContainer container)
{
this.container = container;
}
public object Resolve(Type serviceType, bool ifUnresolvedReturnDefault)
{
return ResolveFromDependencyService(serviceType);
}
public object Resolve(Type serviceType, object serviceKey, bool ifUnresolvedReturnDefault,
Type requiredServiceType,
RequestInfo preResolveParent, IScope scope)
{
return ResolveFromDependencyService(serviceType);
}
public IEnumerable<object> ResolveMany(Type serviceType, object serviceKey, Type requiredServiceType,
object compositeParentKey,
Type compositeParentRequiredType, RequestInfo preResolveParent, IScope scope)
{
return new[] { ResolveFromDependencyService(serviceType) };
}
private static object ResolveFromDependencyService(Type targetType)
{
if (!targetType.GetTypeInfo().IsInterface)
{
return null;
}
var method = typeof(DependencyService).GetTypeInfo().GetDeclaredMethod("Get");
var genericMethod = method.MakeGenericMethod(targetType);
return genericMethod.Invoke(null, new object[] { DependencyFetchTarget.GlobalInstance });
}
....
}
Thanks and looking forward to test DryIoc since I've read it's supposed to be the fastest out there
Updated answer:
You may directly use WithUnknownServiceResolvers returning DelegateFactory:
var c = new Container(Rules.Default.WithUnknownServiceResolvers(request =>
new DelegateFactory(_ => GetFromDependencyService(request.ServiceType))));
No need to implement IContainer just for that.
I think it may be optimized regarding performance by replacing DelegateFactory with ExpressionFactory. But I need some time to play with the idea.

How do I cast a function with a derived argument to a function with a base argument?

I have a class named Reciever that has a function called recieve(const Event *), where Event inherits from BaseEvent. I want to create a bind to a specific instance of that class. The instance is called rec. To do this I use:
void(Reciever::*func)(const Event *) = &Reciever::recieve;
auto recievePtr = std::bind(func, &rec, std::placeholders::_1);
However, when I try to store this in a vector, I have to specify an std::function that takes a BaseEvent as the input, not an Event, like so:
std::vector<std::function<void(const BaseEvent*)>>
How can I cast recievePtr so I can store it properly in the vector? Is this even possible? The issue with using a function pointer to a BaseEvent is that the Reciever can have multiple recieve() methods with different derived classes all based on BaseEvent
You can try something along the following. This compiled and ran fine on my machine. Visual Studio targeting platform toolset v120.
Reciever rec;
std::vector<std::function<void(const BaseEvent*)>> vector;
vector.push_back(
[&rec](const BaseEvent* event)
{
rec.recieve(static_cast<const Event*>(event));
});
vector.push_back(
[&rec](const BaseEvent* event)
{
rec.recieve(static_cast<const EventD*>(event));
});
const BaseEvent* e = new Event();
const BaseEvent* d = new EventD();
vector[0](e);
vector[1](d);

Lua/Luabind: Objects constructed by objects remain allocated

I have a simple Lua script
function TestFunction(Id)
local Factory = TestParent();
local ChildDirect = TestChild("DirectCall");
local ChildFactory1 = Factory:CreateChild("Factory1");
local ChildFactory2 = Factory:CreateChild("Factory2");
result = Ret()
return result
end
that uses two C++ exposed objects (trough luabind)
void TestParent::RegisterToLua(lua_State* lua)
{
// Export our class with LuaBind
luabind::module(lua)
[
luabind::class_<TestParent>("TestParent")
.def(luabind::constructor<>())
.def("CreateChild", &TestParent::CreateChild)
];
}
void TestChild::RegisterToLua(lua_State* lua)
{
// Export our class with LuaBind
luabind::module(lua)
[
luabind::class_<TestChild>("TestChild")
.def(luabind::constructor<std::string>())
.def("GetValue", &TestChild::GetValue)
];
}
I call the function
luabind::object obj = luabind::call_function< luabind::object >(LuaState, "TestFunction", IdParam);
if ( obj.is_valid() )
{
....
}
lua_gc(LuaState, LUA_GCCOLLECT, 0);
During lua_gc call only Factory and ChildDirect objects are destroyed. ChildFactory1 and ChildFactory2 remains allocated. The lua stack remains balanced (has same value - 5 - some tables ) after the luabind::call_function.
What is the problem ? The objects created by Factory remain somehow referenced ? By who ?
CreateChild body is
TestChild* TestParent::CreateChild(std::string strname)
{
return new TestChild(strname);
}
The ownership of the new constructed object should be taken by lua object and destroyed if ChildFactory1 or ChildFactory2 is nil-ed or out of scope.
adopt: Used to transfer ownership across language boundaries.
module(L)
[
def("create", &create, adopt(result))
];
You should return a smart pointer (i.e. a boost::shared_ptr) from your factory.
see: LuaBind Documentation # smart pointer
and a discussion in the LuaBridge docu

Passing objects into callback function from C++ code

I'm writing Agueas [1] addon for Node.js
For now I have synchronous code, C++ class looks like this:
class LibAugeas : public node::ObjectWrap {
public:
static void Init(Handle<Object> target);
protected:
augeas * m_aug;
LibAugeas();
~LibAugeas();
static Handle<Value> New(const Arguments& args);
static Handle<Value> get (const Arguments& args);
static Handle<Value> set (const Arguments& args);
static Handle<Value> setm (const Arguments& args);
// other methods
};
Usage of this class in JS:
var lib = require('...');
var aug = new lib.Augeas(...);
aug.set(...);
aug.get(...);
// etc
I'm going to impelement asynchronous code.
The bottleneck is creating augeas object (aug_init) while all or some lenses and files are being loaded and parsed. So the idea is creating augeas object asynchronously, and then pass created JS object in a callback function:
Pure C thread: call aug_init(), aug_load() to get augeas handle.
When ready, use augeas handle to creat JS object (see the first snippet)
Pass created JS object to callback function.
Usage might be as such:
lib.heracles(function(aug) {
if (!aug.error()) {
console.log('Hello!');
// async save:
aug.save(function(err, msg) {
console.log(msg);
});
} else {
console.log('Sad, but true :-(');
}
}
);
And finally, my problem: I do not know how to create JS object in C++ :-)
Constructor static Handle<Value> New(const Arguments& args); returns args.This(), but when I'm in C++ code I do not have args and also can't wrap object.
So, how do I create JS object in C++? Please, don't break my heart saying it is not possible :-)
[1] http://augeas.net
Ok, thanks to everyone :-)
I've found the right way. Here is a static method which creates an JS object wrapping given augeas handle.
Then I can pass this object to callback function from C++ code.
Local<Object> LibAugeas::New(augeas *aug)
{
LibAugeas *obj = new LibAugeas();
obj->m_aug = aug;
Handle<ObjectTemplate> tpl = ObjectTemplate::New();
tpl->SetInternalFieldCount(1); // one field for LibAugeas* pointer (via obj->Wrap())
#define _OBJ_NEW_METHOD(m) NODE_SET_METHOD(tpl, #m, m)
_OBJ_NEW_METHOD(get);
_OBJ_NEW_METHOD(set);
_OBJ_NEW_METHOD(setm);
_OBJ_NEW_METHOD(rm);
_OBJ_NEW_METHOD(mv);
_OBJ_NEW_METHOD(save);
_OBJ_NEW_METHOD(nmatch);
_OBJ_NEW_METHOD(insert);
_OBJ_NEW_METHOD(error);
Local<Object> O = tpl->NewInstance();
obj->Wrap(O);
return O;
}