C++互操作(隐式 PInvoke)的限制

Limitations of C++ Interop (implicit PInvoke)

本文关键字:PInvoke 互操作 隐式 C++      更新时间:2023-10-16

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

Microsoft的文档建议隐式而不是显式。但是关于我能做什么和不能做什么的信息并不多。这在2014年说,隐式不适用于Mono,因此不适用于Linux系统。但是今天是什么情况呢?

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

此致敬意

托尔斯滕

查看 Unity的原生 dll 文件文档,它们表明在使用 Unity 执行 P/调用时应该使用显式互操作。以下是文档中的示例:

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# 代码更容易。然后,您可以使用插件检查器来设置在运行时应使用哪个平台的 dll。