写Unity的C++插件时非常不方便的一点就是,在Unity调试的时候无法显示log。
以下代码是我在编写HoloLens插件时用到的代码。外汇出入金流程http://www.fx61.com/support,时间过去好久了,今天翻到了做个记录。(万能的指针)
UnityDebug.h
include"string.h"
include "stdio.h"
include
define UnityLog(acStr, ...) Debug::L(acStr, ##__VA_ARGS__);
//create by keefor on 20190717
//C++ Call C#
class Debug {
public:
static void(*Log)(char* message, int iSize);
static void L(char* msg, ...);
};// C# call C++
extern "C" _declspec(dllexport) void InitCSharpDelegate(void(*Log)(char* message, int iSize));
UnityDebug.cpp
include "UnityDebug.h"
//create by keefor on 20190717
void(*Debug::Log)(char* message, int iSize);
void Debug::L(char* fmt, ...) {
if(Debug::Log==NULL)return;
char acLogStr[512];// = { 0 };
va_list ap;
va_start(ap, fmt);
vsprintf(acLogStr, fmt, ap);
va_end(ap);
Debug::Log(acLogStr, strlen(acLogStr));
}
extern "C" void InitCSharpDelegate(void(*Log)(char* message, int iSize)) {
Debug::Log = Log;
//UnityLog("Cpp Message:Log has initialized");
}
C++中打印日志
UnityLog("ok");
Unity中代码
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void LogDelegate(IntPtr message, int iSize);
[DllImport("live_streaming", CallingConvention = CallingConvention.Cdecl)]
public static extern void InitCSharpDelegate(LogDelegate log);
//C# Function for C++‘s call
[MonoPInvokeCallback(typeof(LogDelegate))]
public static void LogMessageFromCpp(IntPtr message, int iSize)
{
Debug.Log(Marshal.PtrToStringAnsi(message, iSize));
}
public static void ShowLog()
{
InitCSharpDelegate(LogMessageFromCpp);
}
要在Unity中显示Log的话执行
ShowLog();