![](/img/trans.png)
[英]Unable to log messages to Application Insights using log4net from one of C# console projects
[英]Log4net, sending log messages from a c++ dll to a c# application?
我有一个 WPF/c# 应用程序,它使用 Log4Net 进行日志记录。 此应用程序使用以下方法调用一些 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");
}
我已经使用这个界面很久了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.