jacksondunstan / unitynativescripting Goto Github PK
View Code? Open in Web Editor NEWUnity Scripting in C++
Home Page: https://jacksondunstan.com/articles/3938
License: MIT License
Unity Scripting in C++
Home Page: https://jacksondunstan.com/articles/3938
License: MIT License
As the title indicates, is it possible to enable coroutine in c++.
newbie question.
get it running under macOS, wanna debug with Xcode.
Hello.
I'm very much interested in coding in C++ in Unity and as I was looking for a (proper) way, I stumbled upon this repository. I read the readme and I still have a couple of things unclear.
I know C++, I know Unity but I don't know a bit about how they can be made to work together, nor by your solution neither by official ones.
I think it would be great if you clearly stated differences (ups/downs) between using your Unity Native Scripting solution and the ones that are already offered by Unity (f.i. native plugin). Please make this visible in the readme so people would go with yours without hesitation.
Hi, I need to implement that feature to interact System.string with C++ string, any idea of that?
Found no api to do that, don't wanna implement in C# side, but I reckon conversion in C++ side should be more efficient.
desc:
//a System.String obj
char *str = obj.c_str();
Unity2018.4.5f1, MacOS works fine, but windows crashes.
issue reproduce: When calling MyGameAbstractBaseBallScriptUpdate
CSharp code:
public override void Update()
{
if (CppHandle != 0)
{
int thisHandle = CppHandle;
NativeScript.Bindings.MyGameAbstractBaseBallScriptUpdate(thisHandle);
if (NativeScript.Bindings.UnhandledCppException != null)
{
Exception ex = NativeScript.Bindings.UnhandledCppException;
NativeScript.Bindings.UnhandledCppException = null;
throw ex;
}
}
}
When executes to the line: auto returnValue = Plugin::UnityEngineTimePropertyGetDeltaTime();
It crashes.
C++ code:
System::Single UnityEngine::Time::GetDeltaTime()
{
auto returnValue = Plugin::UnityEngineTimePropertyGetDeltaTime();
if (Plugin::unhandledCsharpException)
{
System::Exception* ex = Plugin::unhandledCsharpException;
Plugin::unhandledCsharpException = nullptr;
ex->ThrowReferenceToThis();
delete ex;
}
return returnValue;
}
Exception thrown at 0x00007FFDE974D5D9 (NativeScript_temp.dll) in Unity.exe: 0xC0000005: Access violation reading location 0x0000000000000000.
Stacktrace:
========== OUTPUTTING STACK TRACE ==================
0x00007FFE2AEBD5D9 (NativeScript_temp) [c:\projects\research\unitycpp\unity\libs\cppsource\nativescript\bindings.cpp:5498] UnityEngine::Time::GetDeltaTime
0x00007FFE2AEA3B9A (NativeScript_temp) [c:\projects\research\unitycpp\unity\libs\cppsource\game\game.cpp:38] MyGame::BallScript::Update
0x00007FFE2AEBFCA7 (NativeScript_temp) [c:\projects\research\unitycpp\unity\libs\cppsource\nativescript\bindings.cpp:5819] MyGameAbstractBaseBallScriptUpdate
0x000000004E2DC2C5 (Mono JIT Code) (wrapper managed-to-native) object:wrapper_native_00007FFE2AEA12AD (int)
0x000000004E367898 (Mono JIT Code) [C:\Projects\Research\unitycpp\Unity\Assets\NativeScript\Bindings.cs:2121] MyGame.BaseBallScript:Update ()
0x000000004EE32FC8 (Mono JIT Code) (wrapper runtime-invoke) object:runtime_invoke_void__this__ (object,intptr,intptr,intptr)
0x00007FFDBABCB970 (mono-2.0-bdwgc) [c:\users\bokken\builds\vm\mono\mono\mini\mini-runtime.c:2809] mono_jit_runtime_invoke
0x00007FFDBAB51922 (mono-2.0-bdwgc) [c:\users\bokken\builds\vm\mono\mono\metadata\object.c:2919] do_runtime_invoke
0x00007FFDBAB5A91F (mono-2.0-bdwgc) [c:\users\bokken\builds\vm\mono\mono\metadata\object.c:2966] mono_runtime_invoke
0x0000000140C03DAA (Unity) scripting_method_invoke
0x0000000140BF400A (Unity) ScriptingInvocation::Invoke
0x0000000140BBCB57 (Unity) MonoBehaviour::CallMethodIfAvailable
0x0000000140BBD271 (Unity) MonoBehaviour::CallUpdateMethod
0x00000001406EEBDC (Unity) BaseBehaviourManager::CommonUpdate<BehaviourManager>
0x00000001406F5266 (Unity) BehaviourManager::Update
0x0000000140960373 (Unity) `InitPlayerLoopCallbacks'::`2'::UpdateScriptRunBehaviourUpdateRegistrator::Forward
0x000000014095EFC7 (Unity) ExecutePlayerLoop
0x000000014095F093 (Unity) ExecutePlayerLoop
0x0000000140962351 (Unity) PlayerLoop
0x0000000141349FDF (Unity) PlayerLoopController::UpdateScene
0x0000000141339383 (Unity) PlayerLoopController::EnterPlayMode
0x0000000141345323 (Unity) PlayerLoopController::SetIsPlaying
0x0000000141348282 (Unity) Application::TickTimer
0x00000001414A4C53 (Unity) MainMessageLoop
0x00000001414A693D (Unity) WinMain
0x000000014249BABA (Unity) __scrt_common_main_seh
0x00007FFE3E237BD4 (KERNEL32) BaseThreadInitThunk
0x00007FFE3EBCCE71 (ntdll) RtlUserThreadStart
Game booted up
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
NativeScript.Bindings:UnityEngineDebugMethodLogSystemObject(Int32) (at Assets\NativeScript\Bindings.cs:1372)
System.Object:wrapper_native_00007FFE2AEA18DE(IntPtr, Int32, InitMode)
NativeScript.Bindings:OpenPlugin(InitMode) (at Assets\NativeScript\Bindings.cs:836)
NativeScript.Bindings:Open(Int32) (at Assets\NativeScript\Bindings.cs:622)
NativeScript.BootScript:Awake() (at Assets\NativeScript\BootScript.cs:36)
(Filename: Assets/NativeScript/Bindings.cs Line: 1372)
Crash!!!
Seems the projects needs minor update for Unity 2019.1.8.
I followed the "Getting started" section in README. There are 3 issues I noticed.
Issue 1
GenerateBindings.cs
didn't compile because of this line (commented out):
After I commented it out and shifted the array indices accordingly I was able to generate the bindings.
When I commented this out, everything started to work.
Issue 3 (not blocking)
One more strange thing is that pressing "Reload native plugin" button in the editor throws an exception, but it's not actually needed (at least on mac) as the game always use the recent version of the plugin. The exception:
NullReferenceException: Object reference not set to an instance of an object
System.Runtime.InteropServices.Marshal.WriteInt64 (System.IntPtr ptr, System.Int32 ofs, System.Int64 val) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)
System.Runtime.InteropServices.Marshal.WriteIntPtr (System.IntPtr ptr, System.Int32 ofs, System.IntPtr val) (at <1f0c1ef1ad524c38bbc5536809c46b48>:0)
NativeScript.Bindings.OpenPlugin (NativeScript.Bindings+InitMode initMode) (at Assets/NativeScript/Bindings.cs:706)
NativeScript.Bindings.Reload () (at Assets/NativeScript/Bindings.cs:638)
NativeScript.Editor.EditorMenus.Reload () (at Assets/NativeScript/Editor/EditorMenus.cs:27)
Sorry if I'm missing something, I didn't read the docs too thoroughly, just wanted to get the thing working. I actually want to make Haskell bindings to Unity ๐
The moving ball will become two static objects, not moving at all, and keeps flashing.
Unity2018.4.5
This is great stuff, thank you!
One thing that bit me for a while, was that the code generation didn't seem to be working. I assumed I was doing something wrong in NativeScriptTypes.json which was causing a problem, but that turned out to not be the case. After debugging the GenerateBindings.cs code, I eventually realized it was silently failing to inject any changes because the line endings on the generated bindings files (cpp,h,cs) had changed to windows format (CRLF). This caused the GenerateBindings code to fail to find the markers it was looking for, when it went to inject modified code. For example, it looks for this marker in bindings.h:
"/BEGIN TYPE DEFINITIONS/\n"
but in my case, that was not found because the line endings were changed to this:
"/BEGIN TYPE DEFINITIONS/\r\n"
I was able to fix the problem by simply changing the line endings back to unix (LF) instead of CRLF, but a better solution might be to ignore or remove unwanted whitespace from the contents of the bindings files, before doing the string compares. Another option might be to remove the \n from the marker string that you are checking for.?
This could probably be chalked up to 'user error', but I'm afraid that others on Windows could easily encounter this problem as well, so making it a bit more bullet-proof would help.
See below for the area of the code I am referring to.
Thanks again!
-Mustafa
GenerateBindings.cs : line 13511
static string InjectIntoString(
string contents,
string beginMarker,
string endMarker,
string text)
{
for (int startIndex = 0; ; )
{
int beginIndex = contents.IndexOf(beginMarker, startIndex);
if (beginIndex < 0)
{
// EXTRA LOGGING CHECK
if (startIndex == 0)
{
Debug.Log("InjectIntoString: Nothing injected, failed to find beginMarker:" + beginMarker);
}
// END EXTRA LOGGING
return contents;
}
...
Hi !
When running the example project and scene, duplicating the "GameObject with a BallScript" GameObject in the Editor or creating a second GameObject with the same component within PluginMain triggers an assertion failure.
Commit: 60450d4
Unity: 2017.4.5f1 64 bit
OS: Windows 10
Compiler: MSVC 2017, 64 bit
This seems to originate from the free list management for whole objects. The following patch seems to partially fix the issue when instantiating a second component within PluginMain.
diff --git a/Unity/Assets/NativeScript/Editor/GenerateBindings.cs b/Unity/Assets/NativeScript/Editor/GenerateBindings.cs
index 013fa39..c988c19 100644
--- a/Unity/Assets/NativeScript/Editor/GenerateBindings.cs
+++ b/Unity/Assets/NativeScript/Editor/GenerateBindings.cs
@@ -10162,9 +10162,9 @@ namespace NativeScript.Editor
outputFirstBoot.Append("\t\t{\n");
outputFirstBoot.Append("\t\t\tPlugin::");
outputFirstBoot.Append(bindingTypeName);
- outputFirstBoot.Append("FreeWholeList[i].Next = Plugin::");
+ outputFirstBoot.Append("FreeWholeList[i].Next = (Plugin::");
outputFirstBoot.Append(bindingTypeName);
- outputFirstBoot.Append("FreeWholeList[i + 1].Next;\n");
+ outputFirstBoot.Append("FreeWholeList + i + 1);\n");
outputFirstBoot.Append("\t\t}\n");
outputFirstBoot.Append("\t\tPlugin::");
I tried current code for iOS but it have some errors. So I tried using a single cpp file with one export method but the bundle created by make file gives linking error in iOS build created by Unity. can you please look into this or guide me.
Hi. I saw in the project's readme that the generator does not support string
yet. I have however added an abstract method taking a string parameter to the AbstractBaseBallScript
class and have implemented it on the C++ side. All I missed was some way to get a const char *
from a String
, so I added a c_str()
method to it, adding binding methods similar to Plugin::StringNew
. This seem to work, and I managed to transfer a C# string from Unity to the C++ side. I am wondering however if I did the right thing and if this could break in some ways. What do you think?
By the way, would it be possible to add conversion from/to std::string to the String class? If you don't want to force people to use the C++ Standard Library you could add some CMake configuration option like USE_STL.
hotreload works fine, but if stop playing, and re-play in Unity Editor, it crashes.
CODE:
void InitPy()
{
System::String msg= System::String("py_start");
UnityEngine::Debug::Log(msg);
py::initialize_interpreter(true);
//py::scoped_interpreter guard{};
try{
py::object mainScope = py::module::import("__main__").attr("__dict__");
py::exec(\
"from clr import UnityEngine\n"
"UnityEngine.Debug.Log('hello')\n"
"import fast_calc\n"
"with open('pyinit.log', 'w') as f:\n"
" f.write(str(fast_calc.add(1, 2)))\n", mainScope);
}
catch(const py::error_already_set& exc)
{
System::String msg= System::String(exc.what());
UnityEngine::Debug::Log(msg);
PyErr_Print();
}
catch(const std::exception &exc)
{
System::String msg= System::String(exc.what());
UnityEngine::Debug::Log(msg);
//\npy::finalize_interpreter();
}
py::finalize_interpreter();
System::String msg2= System::String("py_exit");
UnityEngine::Debug::Log(msg2);
}
Process: Unity [41049]
Path: /Applications/Unity/Unity.app/Contents/MacOS/Unity
Identifier: com.unity3d.UnityEditor5.x
Version: Unity version 2018.4.5f1 (2018.4.5f1)
Code Type: X86-64 (Native)
Parent Process: ??? [1]
Responsible: Unity [41049]
User ID: 501
Date/Time: 2019-08-03 05:50:25.942 +0800
OS Version: Mac OS X 10.14.6 (18G84)
Report Version: 12
Anonymous UUID: 6DB50D53-DA47-9FD4-6E53-08D77FBA2524
Time Awake Since Boot: 61000 seconds
System Integrity Protection: disabled
Crashed Thread: 0 CrBrowserMain Dispatch queue: com.apple.main-thread
Exception Type: EXC_BAD_ACCESS (SIGABRT)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000169b118c0
Exception Note: EXC_CORPSE_NOTIFY
VM Regions Near 0x169b118c0:
VM_ALLOCATE 0000000169884000-0000000169894000 [ 64K] rwx/rwx SM=PRV
-->
__TEXT 0000000169ba0000-0000000169d24000 [ 1552K] r-x/rwx SM=COW /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/Python
Application Specific Information:
abort() called
Thread 0 Crashed:: CrBrowserMain Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x00007fff6fd102c6 __pthread_kill + 10
1 libsystem_pthread.dylib 0x00007fff6fdcbbf1 pthread_kill + 284
2 libsystem_c.dylib 0x00007fff6fc7a6a6 abort + 127
3 com.unity3d.UnityEditor5.x 0x0000000101053a21 HandleSignal(int, __siginfo*, void*) + 81
4 libmono.0.dylib 0x000000016fac0bce mono_chain_signal + 93
5 libmono.0.dylib 0x000000016fa07fd2 mono_sigsegv_signal_handler + 210
6 libsystem_platform.dylib 0x00007fff6fdc0b5d _sigtramp + 29
7 com.unity3d.UnityEditor5.x 0x0000000100589820 mpi_montmul + 1424
8 org.python.python 0x0000000169bff9d2 PyUnicode_FromString + 14
9 org.python.python 0x0000000169c7a9e2 _PySys_BeginInit + 1481
10 org.python.python 0x0000000169c6c056 _Py_InitializeCore_impl + 775
11 org.python.python 0x0000000169c6c505 _Py_InitializeCore + 184
12 org.python.python 0x0000000169c6d222 _Py_InitializeFromConfig + 50
13 org.python.python 0x0000000169c6d34c Py_InitializeEx + 74
14 NativeScript 0x0000000169783e36 pybind11::initialize_interpreter(bool) + 70 (embed.h:109)
15 NativeScript 0x0000000169783b2c InitPy + 60 (Game.cpp:69)
16 NativeScript 0x000000016978462a PluginMain(void*, int, bool) + 314 (Game.cpp:130)
17 NativeScript 0x00000001697d6c25 Init + 2117 (Bindings.cpp:6234)
18 ??? 0x0000000169671ce7 0 + 6063332583
19 ??? 0x0000000169670f99 0 + 6063329177
20 ??? 0x000000016966d1ad 0 + 6063313325
21 ??? 0x000000016966b34b 0 + 6063305547
22 ??? 0x000000013e88907a 0 + 5344104570
23 libmono.0.dylib 0x000000016fa09c5a 0x16fa00000 + 40026
24 libmono.0.dylib 0x000000016fb3685e mono_runtime_invoke + 117
25 com.unity3d.UnityEditor5.x 0x000000010108416a ScriptingInvocation::Invoke(ScriptingExceptionPtr*, bool) + 106
26 com.unity3d.UnityEditor5.x 0x000000010108401b ScriptingInvocation::InvokeChecked(ScriptingExceptionPtr*) + 59
27 com.unity3d.UnityEditor5.x 0x00000001010373d0 MonoBehaviour::CallMethodInactive(ScriptingMethodPtr) + 592
28 com.unity3d.UnityEditor5.x 0x000000010103c078 MonoBehaviour::CallAwake() + 120
29 com.unity3d.UnityEditor5.x 0x000000010103c660 MonoBehaviour::AddToManager() + 384
30 com.unity3d.UnityEditor5.x 0x00000001010ed29c AwakeFromLoadQueue::InvokePersistentManagerAwake(AwakeFromLoadQueue::Item*, unsigned int, AwakeFromLoadMode) + 796
31 com.unity3d.UnityEditor5.x 0x00000001010ece36 AwakeFromLoadQueue::PersistentManagerAwakeFromLoad(int, AwakeFromLoadMode) + 342
32 com.unity3d.UnityEditor5.x 0x0000000100d6be29 LoadSceneOperation::CompleteAwakeSequence() + 649
33 com.unity3d.UnityEditor5.x 0x0000000100d6a522 LoadSceneOperation::IntegrateMainThread() + 514
34 com.unity3d.UnityEditor5.x 0x0000000100d6dc32 PreloadManager::UpdatePreloadingSingleStep(PreloadManager::UpdatePreloadingFlags, int) + 530
35 com.unity3d.UnityEditor5.x 0x0000000100d6e841 PreloadManager::WaitForAllAsyncOperationsToComplete() + 145
36 com.unity3d.UnityEditor5.x 0x000000010137ed90 EditorSceneManager::RestoreSceneBackups(std::__1::vector<EditorSceneBackup, stl_allocator<EditorSceneBackup, (MemLabelIdentifier)111, 16> >&, EditorSceneManager::PlayModeChange, bool) + 1776
37 com.unity3d.UnityEditor5.x 0x00000001019e10be PlayerLoopController::EnterPlayMode(bool) + 590
38 com.unity3d.UnityEditor5.x 0x00000001019d940d PlayerLoopController::SetIsPlaying(bool) + 269
39 com.unity3d.UnityEditor5.x 0x00000001019d81bd Application::TickTimer() + 6909
40 com.unity3d.UnityEditor5.x 0x0000000100701dce -[EditorApplication TickTimer] + 142
41 com.apple.Foundation 0x00007fff45f30c3b __NSFireTimer + 80
42 com.apple.CoreFoundation 0x00007fff43ca3060 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
43 com.apple.CoreFoundation 0x00007fff43ca2c0c __CFRunLoopDoTimer + 851
44 com.apple.CoreFoundation 0x00007fff43ca2752 __CFRunLoopDoTimers + 330
45 com.apple.CoreFoundation 0x00007fff43c83962 __CFRunLoopRun + 2130
46 com.apple.CoreFoundation 0x00007fff43c82ebe CFRunLoopRunSpecific + 455
47 com.apple.HIToolbox 0x00007fff42ee21ab RunCurrentEventLoopInMode + 292
48 com.apple.HIToolbox 0x00007fff42ee1ded ReceiveNextEventCommon + 355
49 com.apple.HIToolbox 0x00007fff42ee1c76 _BlockUntilNextEventMatchingListInModeWithFilter + 64
50 com.apple.AppKit 0x00007fff4127a79d _DPSNextEvent + 1135
51 com.apple.AppKit 0x00007fff4127948b -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1361
52 com.apple.AppKit 0x00007fff412735a8 -[NSApplication run] + 699
53 com.apple.AppKit 0x00007fff41262ae8 NSApplicationMain + 777
54 com.unity3d.UnityEditor5.x 0x000000010072a0fc EditorMain(int, char const**) + 844
55 com.unity3d.UnityEditor5.x 0x000000010072a579 main + 9
56 libdyld.dylib 0x00007fff6fbd53d5 start + 1
Thread 1:
0 libsystem_pthread.dylib 0x00007fff6fdc83f0 start_wqthread + 0
Thread 2:: Profiler.Dispatcher
0 libsystem_kernel.dylib 0x00007fff6fd0a266 semaphore_wait_trap + 10
1 libdispatch.dylib 0x00007fff6fb88bd9 _dispatch_sema4_wait + 16
2 libdispatch.dylib 0x00007fff6fb8939f _dispatch_semaphore_wait_slow + 98
3 com.unity3d.UnityEditor5.x 0x0000000102a5a7b8 PlatformSemaphore::WaitForSignal() + 24
4 com.unity3d.UnityEditor5.x 0x0000000100f3febc profiling::Dispatcher::ThreadFunc(void*) + 76
5 com.unity3d.UnityEditor5.x 0x0000000100e71a62 Thread::RunThreadWrapper(void*) + 1282
6 libsystem_pthread.dylib 0x00007fff6fdc92eb _pthread_body + 126
7 libsystem_pthread.dylib 0x00007fff6fdcc249 _pthread_start + 66
8 libsystem_pthread.dylib 0x00007fff6fdc840d thread_start + 13
Property bug?
{
"Name": "UnityEngine.GameObject",
"Constructors": [
],
"Methods": [
{
"Name": "AddComponent",
"ParamTypes": [],
"GenericParams": [
{
"Types": [
"MyGame.BaseBallScript"
]
}
]
},
{
"Name": "CreatePrimitive",
"ParamTypes": [
"UnityEngine.PrimitiveType"
]
}
],
"Properties":[
{
"Name":"tag",
"Set":{},
"Get":{}
}
]
},
add property tag to gameobject ,build and run ,throw error
NullReferenceException: Object reference not set to an instance of an object
NativeScript.Bindings.UnityEngineMonoBehaviourPropertyGetTransform (Int32 thisHandle) (at Assets/NativeScript/Bindings.cs:1403)
how to fixed?
Hi. Thanks for this amazing project!
I may have noticed an issue in the bindings generator under Windows: it tries to inject code between markers using \n as newline character. Alas, under Windows since the newline characters are \r\n the generator fails finding the beginning marker and silently skips the injection.
This issue prevents adding new types to be generated.
NOT supporting std C++11
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:37:24: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:572:19: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:576:28: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:577:28: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:602:22: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:608:17: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:614:19: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:617:11: error: exception specification of overriding function is more lax than base version
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:619:30: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:627:23: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:635:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:642:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:648:19: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:655:18: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:675:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:679:11: error: exception specification of overriding function is more lax than base version
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:681:36: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:692:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:696:11: error: exception specification of overriding function is more lax than base version
fatal error: too many errors emitted, stopping now [-ferror-limit=]
106 warnings and 20 errors generated.
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:37:24: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:572:19: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:576:28: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:577:28: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:602:22: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:608:17: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:614:19: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:617:11: error: exception specification of overriding function is more lax than base version
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:619:30: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:627:23: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:635:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:642:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:648:19: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:655:18: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:675:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:679:11: error: exception specification of overriding function is more lax than base version
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:681:36: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:692:25: error: use of undeclared identifier 'nullptr'
/Users/xxxx/Projects/UnityCPP/Unity/Temp/StagingArea/Data/il2cppOutput/Bindings.h:696:11: error: exception specification of overriding function is more lax than base version
DLLExport seems not working.
sym.txt
After searching with MachOViewer, All DLLEXPORT defined symbols are missing, contrary to that, others existed.
Undefined symbols for architecture armv7:
"_DestroyBaseScriptBehaviour", referenced from:
_Bindings_DestroyBaseScriptBehaviour_m8902A94D1481D5392530675EDA206EF110B978DA in Bulk_Assembly-CSharp_0.o
_Bindings_DestroyAll_mC7E16F5CEAA259CD101B934545B17961A30AF6D3 in Bulk_Assembly-CSharp_0.o
(maybe you meant: _Bindings_DestroyBaseScriptBehaviour_m8902A94D1481D5392530675EDA206EF110B978DA)
"_Init", referenced from:
_Bindings_Init_mFDCC5D76C6205E05490541E9710E6D9B951879E5 in Bulk_Assembly-CSharp_0.o
_Bindings_OpenPlugin_mCE61B4740ED49E2A40A7E23E0E50AE8DF639EC4F in Bulk_Assembly-CSharp_0.o
(maybe you meant: OBJC_IVAR$_AVFoundationMediaLoader.m_Initialized, _UNITY_TT_Init_Glyph_Loading ,
I really enjoy your project a lot. Spent the last few days using the generator and porting a lot of functions to C++: Vector3, Quaternions, GameObjects, etc.
I am stuck with a fairly simple task though... Though I manage to expose my GameObjects, their names, tags, etc. I am unable to do the most simple task, which is to check if a GameObject's Tag (String) equals another String's value (the Tag of another GameObject)...
How do I use a simple check in C++ whether one GameObject's Name or Tag equals another one's?
Hello, I am posting this new issue because I have a problem that I really don't know how to solve.
Basically, the binding code generation always waits for compilation when I add these lines
{ "Name": "YandereSimulator.AbstractDiscordCodeGenerator", "BaseTypes": [ { "BaseName": "YandereSimulator.DiscordCodeGenerator", "DerivedName": "YandereSimulator.CodeGenerator" } ] }
which I find weird since it is correct based on the template project
when I remove these lines, the binding code is properly generated
and yes, I have an abstract class named AbstractDiscordCodeGenerator so I don't know where the problem could come from
I tried building and using the plugin in Windows and everything worked fine. However, when I built it on Linux and tried running the example bootscene I got the "couldn't open native library" exception.
What I did:
mkdir build
cd build
cmake -G "Unix Makefiles" -DEDITOR=TRUE ..
make
Exception: Couldn't open native library: /home/mycompany/Repos/UnityNativeScripting/Unity/Assets/Plugins/Editor/libNativeScript.so
NativeScript.Bindings.OpenLibrary (System.String path) (at Assets/NativeScript/Bindings.cs:338)
NativeScript.Bindings.OpenPlugin (NativeScript.Bindings+InitMode initMode) (at Assets/NativeScript/Bindings.cs:712)
NativeScript.Bindings.Open (System.Int32 memorySize) (at Assets/NativeScript/Bindings.cs:646)
NativeScript.BootScript.Start () (at Assets/NativeScript/BootScript.cs:39)
CMake version 3.10.2 and Ubuntu 18.04
Any tips?
Hello, How to use pure c not c++
Using Windows 10 and Visual Studio 15 2017. If I follow your instructions under Windows, everything works, and the example ball moves back and forth. But if I click NativeScript -> Generate Bindings, and then go back to Visual Studio to compile, I get several errors from Bindings.cpp:
The reason I wanted to generate the bindings again was to add support for arrays (as you described how to do in another issue). Attached are the generated Bindings.h and Bindings.cpp that give compile errors. Do you know how to make it so that the code generator makes compilable files?
Now,all platforms build successfully,but run error:
iOS๏ผ
DllNotFoundException: Unable to load DLL 'NativeScript': The specified module could not be found.
at NativeScript.Bindings.Init (System.IntPtr memory, System.Int32 memorySize, NativeScript.Bindings+InitMode initMode, System.IntPtr releaseObject, System.IntPtr stringNew, System.IntPtr setException, System.IntPtr arrayGetLength, System.IntPtr enumerableGetEnumerator, System.Int32 maxManagedObjects, System.IntPtr releaseSystemDecimal, System.IntPtr systemDecimalConstructorSystemDouble, System.IntPtr systemDecimalConstructorSystemUInt64, System.IntPtr boxDecimal, System.IntPtr unboxDecimal, System.IntPtr unityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingle, System.IntPtr unityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3, System.IntPtr boxVector3, System.IntPtr unboxVector3, System.IntPtr unityEngineObjectPropertyGetName, System.IntPtr unityEngineObjectPropertySetName, System.IntPtr unityEngineComponentPropertyGetTransform, System.IntPtr unityEngineTransformPropertyGetPosition, System.IntPtr unityEngineTransformPropertySetPosition, System.IntPtr systemCollectionsIEnumeratorPropertyGetCurrent, System.IntPtr systemCollectionsIEnumeratorMethodMoveNext, System.IntPtr unityEngineGameObjectMethodAddComponentMyGameBaseBallScript, System.IntPtr unityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveType, System.IntPtr unityEngineDebugMethodLogSystemObject, System.IntPtr unityEngineMonoBehaviourPropertyGetTransform, System.IntPtr systemExceptionConstructorSystemString, System.IntPtr boxPrimitiveType, System.IntPtr unboxPrimitiveType, System.IntPtr unityEngineTimePropertyGetDeltaTime, System.IntPtr releaseBaseBallScript, System.IntPtr baseBallScriptConstructor, System.IntPtr boxBoolean, System.IntPtr unboxBoolean, System.IntPtr boxSByte, System.IntPtr unboxSByte, System.IntPtr boxByte, System.IntPtr unboxByte, System.IntPtr boxInt16, System.IntPtr unboxInt16, System.IntPtr boxUInt16, System.IntPtr unboxUInt16, System.IntPtr boxInt32, System.IntPtr unboxInt32, System.IntPtr boxUInt32, System.IntPtr unboxUInt32, System.IntPtr boxInt64, System.IntPtr unboxInt64, System.IntPtr boxUInt64, System.IntPtr unboxUInt64, System.IntPtr boxChar, System.IntPtr unboxChar, System.IntPtr boxSingle, System.IntPtr unboxSingle, System.IntPtr boxDouble, System.IntPtr unboxDouble) [0x00000] in <00000000000000000000000000000000>:0
at NativeScript.Bindings.OpenPlugin (NativeScript.Bindings+InitMode initMode) [0x00000] in <00000000000000000000000000000000>:0
(Filename: currently not available on il2cpp Line: -1)
Setting up 2 worker threads for Enlighten.
Thread -> id: 700009a85000 -> priority: 1
Thread -> id: 700009b08000 -> priority: 1
2018-05-02 13:59:44.571819+0800 unityplayground[89052:1933499] [BoringSSL] Function boringssl_session_errorlog: line 2881 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert
2018-05-02 13:59:44.572148+0800 unityplayground[89052:1933499] [BoringSSL] Function boringssl_session_errorlog: line 2881 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert
I built macosx/iOS/Android,there are problems.
Unity Net 3.5 or 4.6 ,Il2CPP or MONO
new GameObject()
But no gameobject is created in scene.
Based on Blog articles, there is a GameObjectNew func can do that?
so the question is, how to create GameObject(or any other Plugin generated object) correctly?
Steps to produce the issue:
Uncheck BootScript in Unity Editor Inspector, and press Play button.
The plugin's PluginMain is called anyway.
The script is actually working nomatter it's active or not.
Unity2018.4.5f1, build with il2cpp on. When exit the program, it crashes.
Path: /Users/USER/*/test.app/Contents/MacOS/test
Identifier: unity.DefaultCompany.UnityPlayground
Version: 1.0 (0)
Code Type: X86-64 (Native)
Parent Process: ??? [1]
Responsible: test [18850]
User ID: 501
Date/Time: 2019-08-04 02:37:15.592 +0800
OS Version: Mac OS X 10.14.6 (18G87)
Report Version: 12
Anonymous UUID: 6DB50D53-DA47-9FD4-6E53-08D77FBA2524
Time Awake Since Boot: 70000 seconds
System Integrity Protection: disabled
Crashed Thread: 45 UnityPreload
Exception Type: EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Signal: Illegal instruction: 4
Termination Reason: Namespace SIGNAL, Code 0x4
Terminating Process: exc handler [18850]
Application Specific Information:
Assertion failed: (value != __null), function GetCurrentThread, file /Applications/Unity/Unity.app/Contents/il2cpp/libil2cpp/os/Thread.cpp, line 271.
Thread 0:: Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x00007fff66b1c9de __ulock_wait + 10
1 libsystem_pthread.dylib 0x00007fff66bdd6de _pthread_join + 358
2 UnityPlayer.dylib 0x000000010444753b PlatformThread::Join(Thread const*) + 283
3 UnityPlayer.dylib 0x0000000104436a7a Thread::WaitForExit(bool) + 42
4 UnityPlayer.dylib 0x000000010436519a PreloadManager::Stop() + 186
5 UnityPlayer.dylib 0x0000000104349eba NotifyPlayerQuit(bool) + 298
6 UnityPlayer.dylib 0x000000010434acda PlayerCleanup(bool) + 26
7 UnityPlayer.dylib 0x0000000104bb8a52 DoQuit(bool) + 34
8 UnityPlayer.dylib 0x0000000104bac95b -[PlayerAppDelegate UpdatePlayer] + 555
9 com.apple.Foundation 0x00007fff3cd3cc3b __NSFireTimer + 80
10 com.apple.CoreFoundation 0x00007fff3aaaf060 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
11 com.apple.CoreFoundation 0x00007fff3aaaec0c __CFRunLoopDoTimer + 851
12 com.apple.CoreFoundation 0x00007fff3aaae752 __CFRunLoopDoTimers + 330
13 com.apple.CoreFoundation 0x00007fff3aa8f962 __CFRunLoopRun + 2130
14 com.apple.CoreFoundation 0x00007fff3aa8eebe CFRunLoopRunSpecific + 455
15 com.apple.HIToolbox 0x00007fff39cee1ab RunCurrentEventLoopInMode + 292
16 com.apple.HIToolbox 0x00007fff39cedee5 ReceiveNextEventCommon + 603
17 com.apple.HIToolbox 0x00007fff39cedc76 _BlockUntilNextEventMatchingListInModeWithFilter + 64
18 com.apple.AppKit 0x00007fff3808679d _DPSNextEvent + 1135
19 com.apple.AppKit 0x00007fff3808548b -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1361
20 com.apple.AppKit 0x00007fff3807f5a8 -[NSApplication run] + 699
21 com.apple.AppKit 0x00007fff3806eae8 NSApplicationMain + 777
22 UnityPlayer.dylib 0x0000000104bba4e9 PlayerMain(int, char const**) + 1881
23 libdyld.dylib 0x00007fff669e53d5 start + 1
Thread 1:
0 libsystem_pthread.dylib 0x00007fff66bd83f0 start_wqthread + 0
Thread 2:: Profiler.Dispatcher
0 libsystem_kernel.dylib 0x00007fff66b1a266 semaphore_wait_trap + 10
1 libdispatch.dylib 0x00007fff66998bd9 _dispatch_sema4_wait + 16
2 libdispatch.dylib 0x00007fff6699939f _dispatch_semaphore_wait_slow + 98
3 UnityPlayer.dylib 0x00000001045bcd19 profiling::Dispatcher::Run() + 185
4 UnityPlayer.dylib 0x00000001045bc79e profiling::Dispatcher::ThreadFunc(void*) + 46
5 UnityPlayer.dylib 0x000000010443691c Thread::RunThreadWrapper(void*) + 1356
6 libsystem_pthread.dylib 0x00007fff66bd92eb _pthread_body + 126
7 libsystem_pthread.dylib 0x00007fff66bdc249 _pthread_start + 66
8 libsystem_pthread.dylib 0x00007fff66bd840d thread_start + 13
Thread 3:
0 libsystem_pthread.dylib 0x00007fff66bd83f0 start_wqthread + 0
Thread 4:
0 libsystem_pthread.dylib 0x00007fff66bd83f0 start_wqthread + 0
Thread 5:
0 libsystem_pthread.dylib 0x00007fff66bd83f0 start_wqthread + 0
Embedding Python by using Pythonnet(a .net cpython wrapper) is working with Unity.
But il2cpp compilation is very headache with that implementation.
Will embed Python directly within UnityNativeScripting a solution?
struct IComparable;
template struct IComparable_1;
IComparableSystem::Double
it says C2989 'System::IComparable': class template has already been declared as a non-class template NativeScript C:\Projects\Research\unitycpp_190809\Unity\Libs\CppSource\NativeScript\Bindings.h
can't use std::string?
how to implement Debug.Log("hello world"+2019)?
There are so many errors, GC is not run on main thread and will not finally lead to crash.
I think it is not professional that you write these misleading contents. From your words i think you are very into C++ and some kind of dislike C#. I hope your 'features' be more reasonable and more convincing.
Forgive my rudeness.
Exception: Method "System.Collections.Generic.List<UnityEngine.Color32>.Add(T)" not found
NativeScript.Editor.GenerateBindings.GetMethod (System.Type type, System.Reflection.MethodInfo[] methods, System.String methodName, System.String[] paramTypeNames, System.String[] genericTypeNames) (at Assets/NativeScript/Editor/GenerateBindings.cs:906)
NativeScript.Editor.GenerateBindings.GetMethod (NativeScript.Editor.GenerateBindings+JsonMethod jsonMethod, System.Type enclosingType, System.Type[] typeTypeParams, System.Type[] genericArgTypes, System.Reflection.MethodInfo[] methods, System.String[] methodGenericTypeNames) (at Assets/NativeScript/Editor/GenerateBindings.cs:3582)
NativeScript.Editor.GenerateBindings.AppendMethod (NativeScript.Editor.GenerateBindings+JsonMethod jsonMethod, System.Reflection.Assembly[] assemblies, System.Type enclosingType, System.Boolean enclosingTypeIsStatic, NativeScript.Editor.GenerateBindings+TypeKind enclosingTypeKind, System.Reflection.MethodInfo[] methods, System.Type[] typeTypeParams, System.Type[] genericArgTypes, System.Int32 indent, NativeScript.Editor.GenerateBindings+StringBuilders builders) (at Assets/NativeScript/Editor/GenerateBindings.cs:3659)
NativeScript.Editor.GenerateBindings.AppendType (NativeScript.Editor.GenerateBindings+JsonType jsonType, System.Type[] genericArgTypes, System.Type type, NativeScript.Editor.GenerateBindings+TypeKind typeKind, System.Type[] typeParams, System.Int32 maxSimultaneous, System.Reflection.Assembly[] assemblies, NativeScript.Editor.GenerateBindings+StringBuilders builders) (at Assets/NativeScript/Editor/GenerateBindings.cs:1856)
NativeScript.Editor.GenerateBindings.AppendType (NativeScript.Editor.GenerateBindings+JsonType jsonType, System.Type type, NativeScript.Editor.GenerateBindings+TypeKind typeKind, System.Reflection.Assembly[] assemblies, System.Int32 defaultMaxSimultaneous, NativeScript.Editor.GenerateBindings+StringBuilders builders) (at Assets/NativeScript/Editor/GenerateBindings.cs:1480)
NativeScript.Editor.GenerateBindings.DoPostCompileWork (System.Boolean canRefreshAssetDb) (at Assets/NativeScript/Editor/GenerateBindings.cs:535)
NativeScript.Editor.GenerateBindings.Generate () (at Assets/NativeScript/Editor/GenerateBindings.cs:374)
NativeScript.Editor.EditorMenus.Generate () (at Assets/NativeScript/Editor/EditorMenus.cs:22)
I had "Arrays": [
{
"Type": "UnityEngine.Color32"
},
{
"Type": "UnityEngine.Vector3"
},
{
"Type": "UnityEngine.Vector2"
},
{
"Type": "System.Int32"
}
]
When you create a new Abstract type for example AbstractBaseBallScript
and you generate the bindings you get BaseBallScript
In your Bindings.cs
. Switching back to unity editor triggers a compilation and no errors. Good.
If you add some more abstract functions to your AbstractBaseBallScript
and switch back to unity editor to re-build your bindings. Unity Editor will have some Errors for you, but this does not prevent you from clicking on Generate Bindings. If you do generate bindings again GenerateBindings
is accessing an older assembly without your changes to AbstractBaseBallScript
. Thus Bindings.cs
will not have your new changes and will continue to give compilation errors.
The only way to fix this is to manually clear out your Bindings.cs
, compile your code with no errors, then click Generate Bindings
. This results with bindings that reflect your changes.
The way I have fixed this currently is by adding a new editor option NativeScript/Delete Bindings
. I call InjectBuilders
and have them clear out the bindings for me. Now I can delete the bindings and compile without errors. One problem that still persists is you still have to fix any other errors from referencing the bindings generated class from your code-base. In my case its just a factory function.
I'm not sure if this is an already solved problem. I would like to know what your thoughts are on this.
If you think the Delete Bindings is a good idea I can create another pull request as well.
I tried adding another abstract method returning bool in the AbstractBaseBallScript example class and calling the generator (after manually adding a stub override in BaseBallScript to prevent a compilation error in Unity), but the return type of the generated C# binding function is always void. This results in a compilation error when building a player for Android. Building for the Editor is working as expected.
The following change seems to fix the issue: (in the file GenerateBindings.cs, at line 8688)
// C# import for the C++ binding function
AppendCsharpImport(
GetTypeName(type),
typeParams,
funcName,
invokeParams,
typeof(void),
builders.CsharpImports);
Into:
// C# import for the C++ binding function
AppendCsharpImport(
GetTypeName(type),
typeParams,
funcName,
invokeParams,
invokeMethod.ReturnType,
builders.CsharpImports);
Hi!
When the NativeScript.dll is used, Unity always crashes because the C++ UnityEngineTimePropertyGetDeltaTime function pointer's return type is System::Single which is diffrent from the return type of the C# delegate UnityEngineTimePropertyGetDeltaTimeDelegateType. UnityEngineTimePropertyGetDeltaTime should return float instead of System::Single.
When I Run Your Project , It Appear Some Wrong "Assets/Plugins/Editor/NativeScript.dll does not exist" How Can I Solve it /.
Is there any plans for WebGL support in the future?
Hello again,
I've noticed functions returning components are surprisingly slow: GetComponent<>(), GetTransform() and AddComponent<>() seem to take significantly more time in C++ than they do in C#.
I've benchmarked with those two scripts:
C#:
int numObjsToInstantiate = 2500;
GameObject go;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i=0; i<numObjsToInstantiate; i++)
{
go = new GameObject();
go.GetComponent<Transform>().parent = transform;
go.AddComponent<MeshFilter>();
go.AddComponent<MeshRenderer>();
}
sw.Stop();
print("Elapsed time: " + sw.ElapsedMilliseconds);
C++
int numObjsToInstantiate = 2500;
std::clock_t start = std::clock();
for (int i = 0; i<numObjsToInstantiate; i++)
{
GameObject go;
go.GetComponent<Transform>().SetParent(GetTransform());
go.AddComponent<MeshFilter>();
go.AddComponent<MeshRenderer>();
}
float diff = (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000);
char buf[256];
sprintf(buf, "Elapsed time: %d ms", (int)diff);
Debug::Log(String(buf));
The C# script runs in roughly 30 milliseconds. The C++ one takes 20 seconds.
I'm using Unity as a scene viewer for data from an old game, meaning I'm building the whole scene in Start() and adding a few hundred/thousands of components, setting parents for transforms, etc. In my case it's no big deal since it only runs once, but I thought the difference was a bit strange.
(I had no performance issue with other parts of the Unity API. I'm even able to load hundreds of textures in less than a second, which is a real delight.)
Debug content: Done generating bindings in 0.0908891 seconds.
But nothing was generated.
My NativeScriptTypes.json content:
{
"Assemblies": [
],
"Types": [
{
"Name": " System.IFormattable"
},
{
"Name": " System.IConvertible"
},
{
"Name": " System.IComparable"
},
{
"Name": "System.IEquatable`1",
"GenericParams": [
{
"Types": [
"System.Boolean"
]
},
{
"Types": [
"System.Char"
]
},
{
"Types": [
"System.SByte"
]
},
{
"Types": [
"System.Byte"
]
},
{
"Types": [
"System.Int16"
]
},
{
"Types": [
"System.UInt16"
]
},
{
"Types": [
"System.Int32"
]
},
{
"Types": [
"System.UInt32"
]
},
{
"Types": [
"System.Int64"
]
},
{
"Types": [
"System.UInt64"
]
},
{
"Types": [
"System.Single"
]
},
{
"Types": [
"System.Double"
]
},
{
"Types": [
"System.Decimal"
]
},
{
"Types": [
"UnityEngine.Vector3"
]
}
]
},
{
"Name": "System.IComparable`1",
"GenericParams": [
{
"Types": [
"System.Boolean"
]
},
{
"Types": [
"System.Char"
]
},
{
"Types": [
"System.SByte"
]
},
{
"Types": [
"System.Byte"
]
},
{
"Types": [
"System.Int16"
]
},
{
"Types": [
"System.UInt16"
]
},
{
"Types": [
"System.Int32"
]
},
{
"Types": [
"System.UInt32"
]
},
{
"Types": [
"System.Int64"
]
},
{
"Types": [
"System.UInt64"
]
},
{
"Types": [
"System.Single"
]
},
{
"Types": [
"System.Double"
]
},
{
"Types": [
"System.Decimal"
]
}
]
},
{
"Name": " System.Runtime.Serialization.IDeserializationCallback"
},
{
"Name": "System.Decimal",
"Constructors": [
{
"ParamTypes": [
"System.Double"
]
},
{
"ParamTypes": [
"System.UInt64"
]
}
]
},
{
"Name": "UnityEngine.Vector3",
"Constructors": [
{
"ParamTypes": [
"System.Single",
"System.Single",
"System.Single"
]
}
],
"Methods": [
{
"Name": "x+y",
"ParamTypes": [
"UnityEngine.Vector3",
"UnityEngine.Vector3"
]
}
]
},
{
"Name": "UnityEngine.Object",
"Properties": [
{
"Name": "name",
"Get": {},
"Set": {}
}
]
},
{
"Name": "UnityEngine.Component",
"Properties": [
{
"Name": "transform",
"Get": {}
}
]
},
{
"Name": "UnityEngine.Transform",
"Properties": [
{
"Name": "position",
"Get": {},
"Set": {
"Exceptions": [
"System.NullReferenceException"
]
}
}
]
},
{
"Name": "UnityEngine.Texture"
},
{
"Name": "UnityEngine.Resources",
"Methods": [
{
"GenericParams": [
{
"Types": [
"UnityEngine.Texture"
]
}
],
"Name": "Load",
"ParamTypes": [
"System.String"
]
}
]
},
{
"Name": "System.Collections.IEnumerator",
"Methods": [
{
"Name": "MoveNext",
"ParamTypes": []
}
],
"Properties": [
{
"Name": "Current",
"Get": {},
"Set": {}
}
]
},
{
"Name": "System.Runtime.Serialization.ISerializable"
},
{
"Name": "System.Runtime.InteropServices._Exception"
},
{
"Name": "UnityEngine.GameObject",
"Constructors": [
],
"Methods": [
{
"Name": "AddComponent",
"ParamTypes": [],
"GenericParams": [
{
"Types": [
"MyGame.BaseBallScript"
]
}
]
},
{
"Name": "CreatePrimitive",
"ParamTypes": [
"UnityEngine.PrimitiveType"
]
}
]
},
{
"Name": "UnityEngine.Debug",
"Methods": [
{
"Name": "Log",
"ParamTypes": [
"System.Object"
]
}
]
},
{
"Name": "UnityEngine.Behaviour"
},
{
"Name": "UnityEngine.MonoBehaviour",
"Properties": [
{
"Name": "transform",
"Get": {},
"Set": {}
}
]
},
{
"Name": "System.Exception",
"Constructors": [
{
"ParamTypes": [
"System.String"
]
}
]
},
{
"Name": "System.SystemException"
},
{
"Name": "System.NullReferenceException"
},
{
"Name": "UnityEngine.PrimitiveType"
},
{
"Name": "UnityEngine.Time",
"Properties": [
{
"Name": "deltaTime",
"Get": {},
"Set": {}
}
]
},
{
"Name": "MyGame.AbstractBaseBallScript",
"BaseTypes": [
{
"BaseName": "MyGame.BaseBallScript",
"DerivedName": "MyGame.BallScript"
}
]
}
],
"Arrays": [
],
"Delegates": [
]
}
IComparable
such types cannot be exported.
Is it possible to have all types exported?
Hello.
I've been running in an issue with arrays. As mentioned in your blog, I tried the following:
"Arrays": [
{
"Type": "System.Single"
}
]
However, once the bindings are generated, Visual Studio tells me that "Generic" does not exist in System::Collections, hence:
template<> struct Array1<System::Single>
cannot inherit from
virtual System::Collections::Generic::IList<System::Single>
I tried with other types, but the result is always the same. Out of curiosity, I also tried to add System.Collections.Generic.List to NativeScriptTypes.json, but GenerateBindings.cs fails to find that class.
Otherwise your library works great for pretty much everything else I've tried, and is simple enough to use. Your blogs also helps a lot understanding how to use it. This makes interfacing with other C++ libraries much easier. Great job !
Hello,
I am planning on using your project for lua bindings instead of moonsharp. As a quick test to see how fast it runs, I spawned 1,000 GameObjects with the BaseBall script.
I also changed the object store both in c# and c++ to allow up to 10,00 objects.
The result was poor, each script was taking 0.078 ms in Editor and 0.070 ms in the Il2cpp build.
I then implemented the BaseBall script in C# and performed the same test.
My results where much better. each script was taking about 0.01 ms to complete in Editor.
This is my first time trying something like this in Unity3d, I read your blog and it looked like you where getting much better results "C++ can still make 13,140 Unity API calls in a single millisecond.". Executing the c++ scripts is taking me 70 - 80 ms, this seems wrong to me.
Is it better to only have one monobehaviour that manages multiple game objects?
Successfully embedded Python to UnityNativeScripting,
but when executing code below:
import UnityEngine
UnityEngine.Debug.Log('hello')
TypeError: Log(): incompatible function arguments. The following argument types are supported:
1. (self: System::Object) -> None
Invoked with: 'helloworld'
At:
(3):
UnityEngine.Debug:Log(Object)
NativeScript.Bindings:UnityEngineDebugMethodLogSystemObject(Int32) (at Assets/NativeScript/Bindings.cs:1372)
The lib I imported into UnityNativeScripting conflicts with new operator when compiling in Windows(VC15)
BUT it compiles fine with Xcode.
So I need to bypass this placement new trick. Any idea would be great^^
{
MyGame::BaseBallScript* memory = Plugin::StoreWholeBaseBallScript();
//MyGame::BallScript* thiz = new (memory) MyGame::BallScript(Plugin::InternalUse::Only, handle);
//return thiz->CppHandle;
MyGame::BallScript* thiz = new (memory) MyGame::BallScript(Plugin::InternalUse::Only, handle);
return 0;
}
Hello again :)
This time I'm having trouble with some functions crashing Unity, and having a hard time nailing down the cause... I was hoping you could help me figure it out.
This is the code I use (can be pasted directly into the sample .cpp file):
Transform t(go.GetTransform());
t.GetLocalToWorldMatrix(); // crash
Matrix4x4::GetIdentity(); // crash
t.GetPosition(); // ok
String layerName("Default");
LayerMask::NameToLayer(layerName); // crash
Oh, and the relevant NativeScriptTypes.json, if that helps:
{
"Name": "UnityEngine.LayerMask",
"Methods": [
{
"Name": "NameToLayer",
"ParamTypes": [
"System.String"
]
}
]
},
{
"Name": "UnityEngine.Transform",
"Properties": [
{
"Name": "position",
"Get": {},
"Set": {
"Exceptions": [
"System.NullReferenceException"
]
}
},
{
"Name": "worldToLocalMatrix",
"Get": {}
},
{
"Name": "localToWorldMatrix",
"Get": {}
}
]
}
I attached a debugger to the Unity Editor, and it doesn't say much (Access violation reading location 0x0, when calling Plugin::UnityEngineTransformPropertyGetLocalToWorldMatrix(Handle);
in the generated bindings). Happens on both Unity 2017 and 2018, on both Debug and Release build, on Windows.
Those methods are pretty straightforward. GetPosition and GetLocalToWorldMatrix are almost identical when decompiling UnityEngine.dll - they are just calls to native code. I thought it might be because it's returning a Matrix4x4, but LayerMask::NameToLayer
crashes too and it's only returning an int...
Out of curiosity, I tried moving those calls to a C# script, then call the C# script from the C++ code - the result was the same.
First of all, thanks for the great work! It helped me get started really quickly with hot reloading native plugins (even though I don't need any of the binding).
Windows locks DLL files that are currently in use, which means the linker can't write to it when you recompile.
This is fairly easily fixed by making a copy of the DLL and loading that instead. You still watch the original DLL for changes and delete the copy whenever you close the plugin.
"Name": "Game.Utils.Logger",
"Methods": [
{
"Name": "info",
"ParamTypes": [
"System.Object[]"
]
},
]
use of undefined type 'System::Array1<System::Object>' NativeScript C:\Projects\Research\unitycpp\Unity\Libs\CppSource\NativeScript\Bindings.cpp 5986
With this config and master codebase no any change, Editor runs fine, il2cpp standalone build crashes, mono standalone build throughs error like this:
If add VisualElement to Types, c++ bindings won't compile at all.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.