Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

Unity控制台显示C++代码中Log

写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();


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...