【问题标题】:Limitations of C++ Interop (implicit PInvoke)C++ 互操作的限制(隐式 PInvoke)
【发布时间】:2020-01-05 00:06:08
【问题描述】:

我想在 C# 中使用一些本机(非托管)C++。我发现我有两个选项,显式和 C++ 互操作(隐式 pinvoke)。

Microsoft's documentation 建议隐式优于显式。但是没有太多关于我可以这样做和不能这样做的信息。 This 在 2014 年表示,implicit 不适用于 Mono,因此不适用于 Linux 系统。但今天的情况如何?

我想通过我的 C# 应用程序在任何平台(win、mac、linux、android、ios)上使用 C++ 库。它是一个用 C++14 编写的仅头文件模板库。我想知道我是否可以使用推荐的 C++ 互操作来执行此操作,或者我是否必须编写 C 样式 API 并为此使用显式 PInvoke。

最好的问候

索斯滕

【问题讨论】:

  • 在询问有关 Unity 的问题时,请务必包含 unity3d 标签。 Unity 有一些与普通编码不同的“最佳实践”,对普通程序的好建议对 Unity 可能是坏建议,添加标签可以让知道差异的人更有可能看到您的问题。
  • 谢谢,但我的问题与 Unity 无关。我需要这个用于“普通”C# 应用程序
  • 我会看看这两个 repos,作者使用 PInvoke 和托管 C++ 包装了相同的库(Bullet 物理引擎)。 github.com/AndresTraks/BulletSharpPInvoke github.com/AndresTraks/BulletSharp 此外,您将需要一些源文件(可能是 C API)来从仅标头库中编译这些模板。
  • 另外,BulletSharpUnity (github.com/Phong13/BulletSharpUnity3d) 在内部使用 BulletSharpPInvoke,以便在包括 Android 在内的多个平台上使用。
  • 这不是你想的那样,在这两种情况下你都需要一个 C++/CLI 编译器。它确实提供了两种方式的选项(直接调用 C 函数与使用 [DllImport])。您永远不会从 C++/CLI 获得跨平台支持,您确实需要提供 C 接口以便使用 [DllImport]。

标签: c# c++ pinvoke


【解决方案1】:

查看Unity's documentation for Native dll files,他们表明在使用 Unity 执行 P/invoke 时应该使用显式互操作。这是他们在文档中的示例:

using UnityEngine;
using System.Runtime.InteropServices;

class SomeScript : MonoBehaviour {

   #if UNITY_IPHONE

   // On iOS plugins are statically linked into
   // the executable, so we have to use __Internal as the
   // library name.
   [DllImport ("__Internal")]

   #else

   // Other platforms load plugins dynamically, so pass the name
   // of the plugin's dynamic library.
   [DllImport ("PluginName")]

   #endif

   private static extern float FooPluginFunction ();

   void Awake () {
      // Calls the FooPluginFunction inside the plugin
      // And prints 5 to the console
      print (FooPluginFunction ());
   }
}

请注意,您无法使用单个 c++ dll 完成所有平台。您需要为每个平台编译一个 dll,您可以将文件放在单独的子文件夹中,以便所有 dll 文件可以使用相同的名称,以使您的 C# 代码更容易。然后您可以使用PluginInspector 来设置在运行时应该使用哪个平台的dll。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    相关资源
    最近更新 更多