c# - Log4net,将日志消息从 c++ dll 发送到 ac# 应用程序?
问题描述
我有一个使用 Log4Net 进行日志记录的 WPF / c# 应用程序。此应用程序使用以下方法调用一些 c++ dll:
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void TestFunction();
我想做的是让 dll 将日志消息发送回 C# 应用程序,以便 c++ 和 c# 中的所有内容都进入同一个日志。这可能吗?
如果是这样,我该怎么做?
解决方案
将 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");
}
我已经使用这个界面很长时间了。
推荐阅读
- javascript - svelte 如何处理进口内部的反应性
- pandas - 如何在 Pandas 中为频率计数绘制条形图?
- c++ - 纠正 Xcode 中的工作流程以避免错误:Architecture x86_64 的重复符号
- python - 有选择地替换字符串中的特定嵌套分隔符(括号),同时尊重嵌套
- android - ExoPlayer 强制用户使用软件解码器进行视频和音频
- c - 如何将 char 用户输入单独格式化为二维数组?
- c# - 使用 Task.Factory.FromAsync 创建基于 I/O 的任务
- kotlin - 在 Kotlin/Tomcat/Eclipse/Maven 项目中使用“启用工作区解析”的先决条件是什么?
- faunadb - 为什么我有一个错误“预期参考,提供对象”?
- javascript - 设计 React Hooks 可以防止 react-hooks/exhaustive-deps 警告