Skip to content

feat: Support the Unmanaged type (#54) #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NativeScript/runtime/Caches.h
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ class Caches {
std::unique_ptr<v8::Persistent<v8::Function>> InteropReferenceCtorFunc = std::unique_ptr<v8::Persistent<v8::Function>>(nullptr);
std::unique_ptr<v8::Persistent<v8::Function>> PointerCtorFunc = std::unique_ptr<v8::Persistent<v8::Function>>(nullptr);
std::unique_ptr<v8::Persistent<v8::Function>> FunctionReferenceCtorFunc = std::unique_ptr<v8::Persistent<v8::Function>>(nullptr);
std::unique_ptr<v8::Persistent<v8::Function>> UnmanagedTypeCtorFunc = std::unique_ptr<v8::Persistent<v8::Function>>(nullptr);
private:
static std::shared_ptr<ConcurrentMap<v8::Isolate*, std::shared_ptr<Caches>>> perIsolateCaches_;
v8::Isolate* isolate_;
Expand Down
29 changes: 29 additions & 0 deletions NativeScript/runtime/DataWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ enum class WrapperType {
FunctionReferenceType = 1 << 17,
ExtVector = 1 << 18,
Worker = 1 << 19,
UnmanagedType = 1 << 20,
};

struct V8Args {
Expand Down Expand Up @@ -403,6 +404,34 @@ class ObjCAllocDataWrapper: public BaseDataWrapper {
Class klass_;
};

class UnmanagedTypeWrapper: public BaseDataWrapper {
public:
UnmanagedTypeWrapper(uint8_t* data, const TypeEncoding* typeEncoding)
: data_(data), typeEncoding_(typeEncoding), valueTaken_(false) {
}

const WrapperType Type() {
return WrapperType::UnmanagedType;
}

uint8_t* Data() {
this->valueTaken_ = true;
return this->data_;
}

const TypeEncoding* TypeEncoding() {
return this->typeEncoding_;
}

bool ValueTaken() {
return this->valueTaken_;
}
private:
uint8_t* data_;
const tns::TypeEncoding* typeEncoding_;
bool valueTaken_;
};

class ObjCDataWrapper: public BaseDataWrapper {
public:
ObjCDataWrapper(id data, const TypeEncoding* typeEncoding = nullptr)
Expand Down
10 changes: 8 additions & 2 deletions NativeScript/runtime/Interop.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ struct MethodCall {
MetaType metaType,
bool provideErrorOutParameter,
bool ownsReturnedObject,
bool returnsUnmanaged,
bool isInitializer)
: context_(context),
isPrimitiveFunction_(isPrimitiveFunction),
Expand All @@ -39,6 +40,7 @@ struct MethodCall {
metaType_(metaType),
provideErrorOutParameter_(provideErrorOutParameter),
ownsReturnedObject_(ownsReturnedObject),
returnsUnmanaged_(returnsUnmanaged),
isInitializer_(isInitializer) {
}

Expand All @@ -54,6 +56,7 @@ struct MethodCall {
MetaType metaType_;
bool provideErrorOutParameter_;
bool ownsReturnedObject_;
bool returnsUnmanaged_;
bool isInitializer_;
};

Expand All @@ -63,7 +66,8 @@ struct CMethodCall: MethodCall {
void* functionPointer,
const TypeEncoding* typeEncoding,
V8Args& args,
bool ownsReturnedObject)
bool ownsReturnedObject,
bool returnsUnmanaged)
: MethodCall(
context,
true,
Expand All @@ -77,6 +81,7 @@ struct CMethodCall: MethodCall {
MetaType::Undefined,
false,
ownsReturnedObject,
returnsUnmanaged,
false) {
}
};
Expand All @@ -102,6 +107,7 @@ struct ObjCMethodCall: public MethodCall {
meta->type(),
meta->hasErrorOutParameter() && args.Length() < meta->encodings()->count - 1,
meta->ownsReturnedCocoaObject(),
false,
meta->isInitializer()) {
}
};
Expand All @@ -113,7 +119,7 @@ class Interop {
static id CallInitializer(v8::Local<v8::Context> context, const MethodMeta* methodMeta, id target, Class clazz, V8Args& args);
static v8::Local<v8::Value> CallFunction(ObjCMethodCall& methodCall);
static v8::Local<v8::Value> CallFunction(CMethodCall& methodCall);
static v8::Local<v8::Value> GetResult(v8::Local<v8::Context> context, const TypeEncoding* typeEncoding, BaseCall* call, bool marshalToPrimitive, std::shared_ptr<v8::Persistent<v8::Value>> parentStruct = nullptr, bool isStructMember = false, bool ownsReturnedObject = false, bool isInitializer = false);
static v8::Local<v8::Value> GetResult(v8::Local<v8::Context> context, const TypeEncoding* typeEncoding, BaseCall* call, bool marshalToPrimitive, std::shared_ptr<v8::Persistent<v8::Value>> parentStruct = nullptr, bool isStructMember = false, bool ownsReturnedObject = false, bool returnsUnmanaged = false, bool isInitializer = false);
static void SetStructPropertyValue(v8::Local<v8::Context> context, StructWrapper* wrapper, StructField field, v8::Local<v8::Value> value);
static void InitializeStruct(v8::Local<v8::Context> context, void* destBuffer, std::vector<StructField> fields, v8::Local<v8::Value> inititalizer);
static void WriteValue(v8::Local<v8::Context> context, const TypeEncoding* typeEncoding, void* dest, v8::Local<v8::Value> arg);
Expand Down
23 changes: 20 additions & 3 deletions NativeScript/runtime/Interop.mm
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include "Pointer.h"
#include "ExtVector.h"
#include "SymbolIterator.h"
#include "UnmanagedType.h"

using namespace v8;

Expand Down Expand Up @@ -715,9 +716,16 @@
*static_cast<T*>((void*)((uint8_t*)destBuffer + position)) = result;
}

Local<Value> Interop::GetResult(Local<Context> context, const TypeEncoding* typeEncoding, BaseCall* call, bool marshalToPrimitive, std::shared_ptr<Persistent<Value>> parentStruct, bool isStructMember, bool ownsReturnedObject, bool isInitializer) {
Local<Value> Interop::GetResult(Local<Context> context, const TypeEncoding* typeEncoding, BaseCall* call, bool marshalToPrimitive, std::shared_ptr<Persistent<Value>> parentStruct, bool isStructMember, bool ownsReturnedObject, bool returnsUnmanaged, bool isInitializer) {
Isolate* isolate = context->GetIsolate();

if (returnsUnmanaged) {
uint8_t* data = call->GetResult<uint8_t*>();
UnmanagedTypeWrapper* wrapper = new UnmanagedTypeWrapper(data, typeEncoding);
Local<Value> result = UnmanagedType::Create(context, wrapper);
return result;
}

if (typeEncoding->type == BinaryTypeEncodingType::ExtVectorEncoding) {
ffi_type* ffiType = FFICall::GetArgumentType(typeEncoding, isStructMember);
const TypeEncoding* innerTypeEncoding = typeEncoding->details.extVector.getInnerType();
Expand Down Expand Up @@ -909,7 +917,7 @@
const TypeEncoding* typeEncoding = wrapper->ParametersEncoding();

Local<Context> context = isolate->GetCurrentContext();
CMethodCall methodCall(context, functionPointer, typeEncoding, args, false);
CMethodCall methodCall(context, functionPointer, typeEncoding, args, false, false);
Local<Value> result = Interop::CallFunction(methodCall);

info.GetReturnValue().Set(result);
Expand Down Expand Up @@ -1406,7 +1414,16 @@
}
}

Local<Value> result = Interop::GetResult(methodCall.context_, methodCall.typeEncoding_, &call, marshalToPrimitive, nullptr, false, methodCall.ownsReturnedObject_, methodCall.isInitializer_);
Local<Value> result = Interop::GetResult(
methodCall.context_,
methodCall.typeEncoding_,
&call,
marshalToPrimitive,
nullptr,
false,
methodCall.ownsReturnedObject_,
methodCall.returnsUnmanaged_,
methodCall.isInitializer_);

return result;
}
Expand Down
5 changes: 3 additions & 2 deletions NativeScript/runtime/MetadataBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -841,7 +841,7 @@
V8VectorArgs vectorArgs(localArgs);
Local<Context> context = Caches::Get(isolate)->GetContext();
v8::Unlocker unlocker(isolate);
CMethodCall methodCall(context, item->userData_, typeEncoding, vectorArgs, item->meta_->ownsReturnedCocoaObject());
CMethodCall methodCall(context, item->userData_, typeEncoding, vectorArgs, item->meta_->ownsReturnedCocoaObject(), false);
Interop::CallFunction(methodCall);
});

Expand All @@ -851,7 +851,8 @@
V8FunctionCallbackArgs args(info);
const TypeEncoding* typeEncoding = item->meta_->encodings()->first();
Local<Context> context = isolate->GetCurrentContext();
CMethodCall methodCall(context, item->userData_, typeEncoding, args, item->meta_->ownsReturnedCocoaObject());
const FunctionMeta* funcMeta = item->meta_;
CMethodCall methodCall(context, item->userData_, typeEncoding, args, funcMeta->ownsReturnedCocoaObject(), funcMeta->returnsUnmanaged());
Local<Value> result = Interop::CallFunction(methodCall);

if (typeEncoding->type != BinaryTypeEncodingType::VoidEncoding) {
Expand Down
7 changes: 7 additions & 0 deletions NativeScript/runtime/ObjectManager.mm
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@
}
break;
}
case WrapperType::UnmanagedType: {
UnmanagedTypeWrapper* unmanagedTypeWrapper = static_cast<UnmanagedTypeWrapper*>(wrapper);
if (unmanagedTypeWrapper != nullptr) {
delete unmanagedTypeWrapper;
}
break;
}
case WrapperType::Block: {
BlockWrapper* blockWrapper = static_cast<BlockWrapper*>(wrapper);
std::free(blockWrapper->Block());
Expand Down
21 changes: 21 additions & 0 deletions NativeScript/runtime/UnmanagedType.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#ifndef UnmanagedType_h
#define UnmanagedType_h

#include "Common.h"
#include "DataWrapper.h"

namespace tns {

class UnmanagedType {
public:
static v8::Local<v8::Value> Create(v8::Local<v8::Context> context, UnmanagedTypeWrapper* wrapper);
private:
static void ConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info);
static void TakeUnretainedValueCallback(const v8::FunctionCallbackInfo<v8::Value>& info);
static void TakeRetainedValueCallback(const v8::FunctionCallbackInfo<v8::Value>& info);
static v8::Local<v8::Value> TakeValue(const v8::FunctionCallbackInfo<v8::Value>& info, bool retained);
};

}

#endif /* UnmanagedType_h */
89 changes: 89 additions & 0 deletions NativeScript/runtime/UnmanagedType.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#include "UnmanagedType.h"
#include "NativeScriptException.h"
#include "Caches.h"
#include "Helpers.h"
#include "Interop.h"

using namespace v8;

namespace tns {

Local<Value> UnmanagedType::Create(Local<Context> context, UnmanagedTypeWrapper* wrapper) {
Isolate* isolate = context->GetIsolate();
auto cache = Caches::Get(isolate);
if (cache->UnmanagedTypeCtorFunc.get() == nullptr) {
Local<FunctionTemplate> ctorFuncTemplate = FunctionTemplate::New(isolate, ConstructorCallback);
ctorFuncTemplate->SetClassName(tns::ToV8String(isolate, "Unmanaged"));
Local<ObjectTemplate> proto = ctorFuncTemplate->PrototypeTemplate();

Local<FunctionTemplate> takeUnretainedValueFuncTemplate = FunctionTemplate::New(isolate, UnmanagedType::TakeUnretainedValueCallback);
Local<FunctionTemplate> takeRetainedValueFuncTemplate = FunctionTemplate::New(isolate, UnmanagedType::TakeRetainedValueCallback);
proto->Set(tns::ToV8String(isolate, "takeUnretainedValue"), takeUnretainedValueFuncTemplate);
proto->Set(tns::ToV8String(isolate, "takeRetainedValue"), takeRetainedValueFuncTemplate);

Local<v8::Function> ctorFunc;
bool success = ctorFuncTemplate->GetFunction(context).ToLocal(&ctorFunc);
tns::Assert(success, isolate);

cache->UnmanagedTypeCtorFunc = std::make_unique<Persistent<v8::Function>>(isolate, ctorFunc);
}

Local<External> ext = External::New(isolate, wrapper);

Local<v8::Function> ctorFunc = cache->UnmanagedTypeCtorFunc->Get(isolate);
Local<Value> result;
Local<Value> args[] = { ext };
bool success = ctorFunc->NewInstance(context, 1, args).ToLocal(&result);
tns::Assert(success, isolate);

return result;
}

void UnmanagedType::ConstructorCallback(const FunctionCallbackInfo<Value>& info) {
Local<External> ext = info[0].As<External>();
UnmanagedTypeWrapper* wrapper = static_cast<UnmanagedTypeWrapper*>(ext->Value());
tns::SetValue(info.GetIsolate(), info.This(), wrapper);
}

void UnmanagedType::TakeUnretainedValueCallback(const FunctionCallbackInfo<Value>& info) {
try {
info.GetReturnValue().Set(UnmanagedType::TakeValue(info, false));
} catch (NativeScriptException& ex) {
ex.ReThrowToV8(info.GetIsolate());
}
}

void UnmanagedType::TakeRetainedValueCallback(const FunctionCallbackInfo<Value>& info) {
try {
info.GetReturnValue().Set(UnmanagedType::TakeValue(info, true));
} catch (NativeScriptException& ex) {
ex.ReThrowToV8(info.GetIsolate());
}
}

Local<Value> UnmanagedType::TakeValue(const FunctionCallbackInfo<Value>& info, bool retained) {
Isolate* isolate = info.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();

BaseDataWrapper* baseWrapper = tns::GetValue(isolate, info.This());
UnmanagedTypeWrapper* wrapper = static_cast<UnmanagedTypeWrapper*>(baseWrapper);

if (wrapper->ValueTaken()) {
throw NativeScriptException("Unmanaged value has already been consumed.");
}

uint8_t* data = wrapper->Data();
const TypeEncoding* typeEncoding = wrapper->TypeEncoding();

BaseCall call((uint8_t*)&data);
Local<Value> result = Interop::GetResult(context, typeEncoding, &call, false);

if (retained) {
id value = static_cast<id>((void*)data);
[value release];
}

return result;
}

}
52 changes: 26 additions & 26 deletions TestRunner/app/tests/ApiTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -584,35 +584,35 @@ describe(module.id, function () {
expect(TNSMutableObjectGet() instanceof NSObject).toBe(true);
});

// it("returns retained", function () {
// expect(functionReturnsNSRetained().retainCount()).toBe(1);
// expect(functionReturnsCFRetained().retainCount()).toBe(1);
// expect(functionImplicitCreate().retainCount()).toBe(1);

// var obj = functionExplicitCreateNSObject();
// expect(obj.retainCount()).toBe(2);
// CFRelease(obj);

// expect(TNSReturnsRetained.methodReturnsNSRetained().retainCount()).toBe(1);
// expect(TNSReturnsRetained.methodReturnsCFRetained().retainCount()).toBe(1);
// expect(TNSReturnsRetained.newNSObjectMethod().retainCount()).toBe(1);
// });
it("returns retained", function () {
expect(functionReturnsNSRetained().retainCount()).toBe(1);
expect(functionReturnsCFRetained().retainCount()).toBe(1);
expect(functionImplicitCreate().retainCount()).toBe(1);

var obj = functionExplicitCreateNSObject();
expect(obj.retainCount()).toBe(2);
CFRelease(obj);

expect(TNSReturnsRetained.methodReturnsNSRetained().retainCount()).toBe(1);
expect(TNSReturnsRetained.methodReturnsCFRetained().retainCount()).toBe(1);
expect(TNSReturnsRetained.newNSObjectMethod().retainCount()).toBe(1);
});

// it("unmanaged", function () {
// var unmanaged = functionReturnsUnmanaged();
// expect('takeRetainedValue' in unmanaged).toBe(true);
// expect('takeUnretainedValue' in unmanaged).toBe(true);
// expect(functionReturnsUnmanaged().takeRetainedValue().retainCount()).toBe(1);
it("unmanaged", function () {
var unmanaged = functionReturnsUnmanaged();
expect('takeRetainedValue' in unmanaged).toBe(true);
expect('takeUnretainedValue' in unmanaged).toBe(true);
expect(functionReturnsUnmanaged().takeRetainedValue().retainCount()).toBe(1);

// var value = functionReturnsUnmanaged().takeUnretainedValue();
// expect(value.retainCount()).toBe(2);
// CFRelease(value);
var value = functionReturnsUnmanaged().takeUnretainedValue();
expect(value.retainCount()).toBe(2);
CFRelease(value);

// unmanaged.takeRetainedValue();
// expect(function() {
// unmanaged.takeUnretainedValue();
// }).toThrow();
// });
unmanaged.takeRetainedValue();
expect(function() {
unmanaged.takeUnretainedValue();
}).toThrow();
});

it('methods can be recursively called', function() {
var result = TNSTestNativeCallbacks.callRecursively(function() {
Expand Down
Loading