A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

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

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马