Create C++ static initializer for use in global objects. (#115)

This commit is contained in:
Nikolay Igotti
2016-12-05 14:01:24 +03:00
committed by GitHub
parent 737a132b5d
commit 1197b8453f
4 changed files with 39 additions and 5 deletions
+2 -2
View File
@@ -9,7 +9,8 @@ ArrayHeader* setupArgs(int argc, char** argv) {
ArrayHeader* args = AllocArrayInstance(theArrayTypeInfo, SCOPE_GLOBAL, argc-1);
for (int i = 0; i < argc-1; i++) {
Kotlin_Array_set(args, i, AllocStringInstance( argv[i+1], strlen(argv[i+1]) ));
Kotlin_Array_set(args, i, AllocStringInstance(
SCOPE_GLOBAL, argv[i+1], strlen(argv[i+1]) ));
}
return args;
@@ -27,4 +28,3 @@ int main(int argc, char** argv) {
// Yes, we have to follow Java convention and return zero.
return 0;
}
+1 -1
View File
@@ -36,7 +36,7 @@ class AutoFree {
// TODO: this method ignores the encoding
KString CreateKotlinStringFromCString(const char* str) {
return AllocStringInstance(str, strlen(str));
return AllocStringInstance(SCOPE_GLOBAL, str, strlen(str));
}
#ifdef __cplusplus
+31 -1
View File
@@ -89,7 +89,8 @@ ArrayHeader* AllocArrayInstance(
return ArrayContainer(type_info, elements).GetPlace();
}
ArrayHeader* AllocStringInstance(const char* data, uint32_t length) {
ArrayHeader* AllocStringInstance(
PlacementHint hint, const char* data, uint32_t length) {
ArrayHeader* result = ArrayContainer(theStringTypeInfo, length).GetPlace();
memcpy(
ByteArrayAddressOfElementAt(result, 0),
@@ -97,6 +98,35 @@ ArrayHeader* AllocStringInstance(const char* data, uint32_t length) {
length);
return result;
}
ObjHeader* InitInstance(
ObjHeader** location, const TypeInfo* type_info, PlacementHint hint,
void (*ctor)(ObjHeader*)) {
ObjHeader* sentinel = reinterpret_cast<ObjHeader*>(1);
ObjHeader* value;
// Wait until other initializers.
while ((value = __sync_val_compare_and_swap(
location, nullptr, sentinel)) == sentinel) {
// TODO: consider yielding.
}
if (value != nullptr) {
// OK'ish, inited by someone else.
return value;
}
ObjHeader* instance = AllocInstance(type_info, hint);
try {
ctor(instance);
__sync_val_compare_and_swap(location, sentinel, instance);
return instance;
} catch (...) {
Release(instance->container());
__sync_val_compare_and_swap(location, sentinel, nullptr);
return nullptr;
}
}
#ifdef __cplusplus
}
#endif
+5 -1
View File
@@ -254,7 +254,11 @@ void InitMemory();
ObjHeader* AllocInstance(const TypeInfo* type_info, PlacementHint hint);
ArrayHeader* AllocArrayInstance(
const TypeInfo* type_info, PlacementHint hint, uint32_t elements);
ArrayHeader* AllocStringInstance(const char* data, uint32_t length);
ArrayHeader* AllocStringInstance(PlacementHint hint,
const char* data, uint32_t length);
ObjHeader* InitInstance(
ObjHeader** location, const TypeInfo* type_info, PlacementHint hint,
void (*ctor)(ObjHeader*));
#ifdef __cplusplus
}