使用本机库Using Native Libraries

Xamarin.Android 支持通过标准的 PInvoke 机制的本机库的使用。Xamarin.Android supports the use of native libraries via the standard PInvoke mechanism. 此外可以绑定其他本机库,后者不是你.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.Android 必须知道本机库专为哪个 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 将被"探查"为armeabiThus, 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++添加到项目引用在 Xamarin.Android 解决方案内C++动态共享库 (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 StudioC++开发人员可以查看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.