【问题标题】:Log4net, sending log messages from a c++ dll to a c# application?Log4net,将日志消息从 c++ dll 发送到 c# 应用程序?
【发布时间】:2019-03-04 09:40:39
【问题描述】:

我有一个使用 Log4Net 进行日志记录的 WPF / c# 应用程序。此应用程序使用以下方法调用一些 c++ dll:

[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void TestFunction();

我想做的是让 dll 将日志消息发送回 C# 应用程序,以便 c++ 和 c# 中的所有内容都进入同一个日志。这可能吗?

如果是这样,我该怎么做?

【问题讨论】:

  • DLL 是否在您的控制之下?你可以修改它们吗?那么你可以为日志函数(“delegate”)添加一个参数吗?
  • 是的,我已经编写了 dll 以及 c#。你能再解释一下吗?或指向我一些参考?谢谢。

标签: c# c++ log4net


【解决方案1】:

将c++ dill中的日志重定向到c#回调的示例:

c#端:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate void LogCallback([MarshalAs(UnmanagedType.LPWStr)] string info);

namespace WinApp
{
  static class Wrapper
  {
    [DllImport("target.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
    public static extern void SetLogCallback([MarshalAs(UnmanagedType.FunctionPtr)] LogCallback callbackPointer);

    internal static void Init()
    {
      LogCallback log_cb = (info) =>
      {
        Console.Write(DateTime.Now.TimeOfDay.ToString() + " " + info);
      };
      SetLogCallback(log_cb);
    }
  }

c++端(编译于target.dll):

extern "C" {
    typedef char* (__stdcall* LogCallback)(const wchar_t* info);
    PEPARSER_API void SetLogCallback(LogCallback cb);
}

static LogCallback global_log_cb = nullptr;


void LogInfo(const wchar_t* info) {
    if (global_log_cb) {
        std::wstring buf = L"[PEParse]" + std::wstring(info) + L"\n";
        global_log_cb(buf.c_str());
    }
    else {
        std::cout << "global_log_cb not set\n";
    }
}

void LogInfo(const char* info) {
    const size_t cSize = strlen(info) + 1;

    size_t t;

    std::wstring wstr(cSize, L'#');
    mbstowcs_s(&t, &wstr[0], cSize, info, cSize - 1);

    LogInfo(&wstr[0]);
}

void SetLogCallback(LogCallback cb) {
    global_log_cb = cb;
    LogInfo("log init");
}

这个界面我用了很久了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 2020-11-01
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多