Unity控制台显示C++ dll库中Log

写Unity的C++插件时非常不方便的一点就是,在Unity调试的时候无法显示log。

以下代码是我在编写HoloLens插件时用到的代码。时间过去好久了,今天翻到了做个记录。(万能的指针)

UnityDebug.h


#include"string.h"
#include "stdio.h"
#include <stdarg.h>
#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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值