【问题标题】:Mono C# PInvoke - Get CFString from external libMono C# PInvoke - 从外部库获取 CFString
【发布时间】:2011-08-11 14:48:40
【问题描述】:

我有一个返回 CFString 的库,我正在尝试在 C# 中获取该字符串值。 问题是我不知道如何在 C# 中做到这一点..

使外部函数返回 CFString 不起作用,因为它会引发异常“传递给非托管代码的类型 MonoMac.CoreFoundation.CFString 必须具有 StructLayout 属性。”

然后我认为我可以将字符串作为字节数组获取,然后将其转换为 C# 中的字符串,但是,我有另一个问题,我不知道如何在 C 中将 CFString 转换为字节数组:/

C# Dll Import stuff
[DllImport("lib")]
public static extern MonoMac.CoreFoundation.CFString  test();   

[DllImport("lib")]
public static extern byte[] test();     


C Library sample
CFStringRef test()
{
return CFSTR("test string");
}

如果有人知道如何做到这一点,请帮助我;)

谢谢

【问题讨论】:

  • Mono 的默认调用约定是什么?您应该在 C 代码和 C# 中声明它并确保它们匹配。

标签: c# c mono monomac cfstring


【解决方案1】:

试试:

 [DllImport("lib")]
 public static extern IntPtr test();

然后使用:

 new CFString (test ()).ToString ();

【讨论】:

    【解决方案2】:
    1. 使用 UnixMarshal.StringToHeap 将字符串转换为 IntPtr。
    2. 使用 UnixMarshal.PtrToString 将 IntPtr 转换为字符串。

    【讨论】:

      猜你喜欢
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多