Comrades, tell me what’s the matter. There is a code like this:
Side - Unity (c#)
public class TestClass : MonoBehaviour
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate bool Delegate_InitializeNativeDLL(IntPtr ptr);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate IntPtr Delegate_GetRenderEvent();
static InitializeNativeDLL _InitializeCore;
static GetRenderEvent _GetRenderEvent;
static private IntPtr pointerDll = IntPtr.Zero;
private void Start()
{
............
skipped loading library with (LoadLibrary)
............
IntPtr func;
func = GetProcAddress(pointerDll, "InitializeNativeDLL");
if (func != null)
_InitializeNativeDLL= Marshal.GetDelegateForFunctionPointer<Delegate_InitializeNativeDLL>(func);
func = GetProcAddress(pointerDll, "GetRenderEventFunc");
if (func != null)
_GetRenderEvent = Marshal.GetDelegateForFunctionPointer<Delegate_GetRenderEvent>(func);
_InitializeNativeDLL( Marshal.GetFunctionPointerForDelegate<Delegate_GetRenderEvent>(_Callback_FromNative))
// Run function!!!!!!!!!!
update_func(1);
}
static void _Callback_FromNative(IntPtr data)
{
Debug.Log("Run UnityFunc from native side");
}
static public void update_func(int mode)
{
GL.IssuePluginEvent(_GetRenderEvent(), mode);
}
private void OnDestroy()
{
FreeLibrary(pointerDll);
}
Side - Native (C++)
typedef void (*_v_function_pv)(void*);
_v_function_pv _callbackTest = nullptr;
extern "C"
{
UNITY_INTERFACE_EXPORT bool InitializeNativeDLL(void* _Callback_In)
{
_callbackTest = (_v_function_pv)_Callback_In;
return true;
}
// Plugin function to handle a specific rendering event
static void UNITY_INTERFACE_API OnRenderEvent(int eventID)
{
_callbackTest (nullptr);
}
// Freely defined function to pass a callback to plugin-specific scripts
extern "C" UnityRenderingEvent UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API
GetRenderEventFunc()
{
return OnRenderEvent;
}
At the first start (Start) everything goes fine. DebugLog gives “Run UnityFunc from native side”. But when you want to re-launch (click on play) the editor freezes. You have to force it to terminate and restart Unity.
But, if I remove this line from the native side
// Plugin function to handle a specific rendering event
static void UNITY_INTERFACE_API OnRenderEvent (int eventID)
{
// _callbackTest (nullptr);
}
then everything works fine, nothing crashes.
Even if you run _callbackTest (nullptr) with the InitializeNativeDLL function. Everything is OK. But it is worth moving to OnRenderEvent (int eventID) problems begin. Although the first launch goes well.