如何P /调用os_log?

时间:2018-12-10 18:50:13

标签: c# macos .net-core pinvoke oslog

在.NET Core控制台应用程序中从C#调用MacOS的os_log的语法应该是什么?

基于
https://developer.apple.com/documentation/os/os_log

How to use iOS OSLog with Xamarin?

https://opensource.apple.com/source/xnu/xnu-4903.221.2/libkern/os/log.h.auto.html
我期待这样的事情:

using System.Runtime.InteropServices;

namespace Foo 
{
 class Program
 {
  [DllImport("__Internal", EntryPoint = "os_log_create")]
  private static extern IntPtr os_log_create(string subsystem, string category);

  [DllImport("__Internal", EntryPoint = "os_log")]
  private static extern void os_log(IntPtr log, string format, string message);

  static void Main(string[] args)
  {  
   IntPtr log = os_log_create("some.bundle.id", "SomeCategory");
   os_log(log, "%s", "Test!");
  }
 }
}

但是,当我尝试在Mac上运行此程序时,我得到一个System.DllNotFoundException,上面写着Unable to load shared library '__Internal' or one of its dependencies...

任何有关此问题或C#和MacOS之间的P / Invoke的帮助都将非常有帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

宏os_log

与os_log_create函数相比,os_log是一个宏,如注释中所述。

所以,如果您要用C编写:

os_log(log, "%{public}s", "Test!");

它最终将调用一个名为_os_log_impl的函数,但该函数的第一个参数将是指针__dso_handle,我们无法从托管端访问该指针。

可能的解决方案

但是,如果没有Apple的新日志记录系统,您不必做任何事情。一种可能性是创建一个动态库,该库提供可从托管C#代码轻松调用的已定义API。

如何在Xcode中创建动态库

在Xcode中创建动态库很容易:

  • 在XCode中选择<文件/新项目>

  • macOS 部分

  • 中选择 Library 模板
  • 使用类型动态

最小示例

我们自己的 Logging 库的最小.c示例如下所示:

 #include <os/log.h>

 extern void Log(os_log_t log, char *message) {
     os_log(log, "%{public}s", message);
 }

从.Net拨打电话

我拿走了你的资料,只是对其做了些微修改:

using System;
using System.Runtime.InteropServices;

namespace Foo 
{
    class Program
    {
        [DllImport("System", EntryPoint = "os_log_create")]
        private static extern IntPtr os_log_create(string subsystem, string category);

        [DllImport("Logging", EntryPoint = "Log")]
        private static extern void Log(IntPtr log, string msg);

        static void Main(string[] args)
        {  
            IntPtr log = os_log_create("some.bundle.id", "SomeCategory");
            Log(log, "Test!");
        }
    }
}

使用Xcode创建的动态库的名称为 Logging 。我们在C中创建的日志记录功能在此处名为 Log

当然,您可以根据需要设计API,这应该是一个尽可能接近问题的最小示例。

控制台实用程序中的输出

控制台实用程序中的输出(如果您过滤 some.bundle.id )将如下所示:

output in Console utility

相关问题