使用本机库Using Native Libraries

Xamarin 支持通过标准 PInvoke 机制使用本机库。Xamarin.Android supports the use of native libraries via the standard PInvoke mechanism. 你还可以将不属于 OS 的其他本机库绑定到你的 apk。You can also bundle additional native libraries which are not part of the OS into your .apk.

若要使用 Xamarin Android 应用程序部署本机库,请将库的二进制文件添加到项目中,并将其生成操作设置为AndroidNativeLibraryTo deploy a native library with a Xamarin.Android application, add the library binary to the project and set its Build Action to AndroidNativeLibrary.

若要使用 Xamarin Android 库项目部署本机库,请将库的二进制文件添加到项目,并将其生成操作设置为EmbeddedNativeLibraryTo deploy a native library with a Xamarin.Android library project, add the library binary to the project and set its Build Action to EmbeddedNativeLibrary.

请注意,由于 Android 支持多个应用程序二进制接口(Abi),因此,Xamarin 必须知道为其生成本机库的 ABI。Note that since Android supports multiple Application Binary Interfaces (ABIs), Xamarin.Android must know which ABI the native library is built for. 可以通过两种方法完成:There are two ways this can be done:

  1. 路径 "窃听"Path "sniffing"
  2. 通过使用AndroidNativeLibrary/Abi项目文件中的元素By using an AndroidNativeLibrary/Abi element within the project file

通过路径探查,本机库的父目录名称用于指定库的目标 ABI。With path sniffing, the parent directory name of the native library is used to specify the ABI that the library targets. 因此,如果将添加lib/armeabi/libfoo.so到项目,则 ABI 将为 "探查armeabi"。Thus, if you add lib/armeabi/libfoo.so to the project, then the ABI will be "sniffed" as armeabi.

或者,你可以编辑项目文件以显式指定要使用的 ABI:Alternatively, you can edit your project file to explicitly specify the ABI to use:

<ItemGroup>
    <AndroidNativeLibrary Include="path/to/libfoo.so">
        <Abi>armeabi</Abi>
    </AndroidNativeLibrary>
</ItemGroup>

有关使用本机库的详细信息,请参阅使用本机库的互操作For more information about using native libraries, see Interop with native libraries.

在 Visual Studio 中调试本机代码Debugging Native Code with Visual Studio

如果使用的是Visual studio 2019visual studio 2017,则无需像上文所述修改项目文件。If you're using Visual Studio 2019 or Visual Studio 2017, you don't have to modify your project files as described above. 可以通过添加对C++ C++ 动态共享库(Android) 项目的项目引用,在 Xamarin Android 解决方案内生成和调试。You can build and debug C++ inside your Xamarin.Android solution by adding a project reference to a C++ Dynamic Shared Library (Android) project.

若要在C++项目中调试本机代码,请执行以下步骤:To debug native C++ code in your project, follow these steps:

  1. 双击 "项目属性",然后选择 " Android 选项" 页。Double-click project Properties and select the Android Options page.
  2. 向下滚动到 "调试选项"。Scroll down to Debugging options.
  3. 调试器下拉菜单中,选择C++ (而不是默认的 .net (Xamarin) )。In the Debugger dropdown menu, select C++ (instead of the default .Net (Xamarin)).

Visual Studio C++开发人员可以查看SanAngeles_NativeDebug示例,尝试从C++ visual Studio 2019 或带 Xamarin 的 visual studio 2017 进行调试;有关详细信息,请参阅我们的博客文章Visual Studio C++ developers can see the SanAngeles_NativeDebug sample to try debugging C++ from Visual Studio 2019 or Visual Studio 2017 with Xamarin; and refer to our blog post for more information.