Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DllImport - DllNotFoundException with android .so

It's the first time I try to create a library c++ for Android/iOS.

I'm using Visual Studio 2015 - Xamarin.

First I created a project : Visual C++ -> Cross Platform -> Shared Library. In the hared library, I created 2 files.

SayHello.h :

#pragma once
#include <string.h>

class SayHello {
public:
    SayHello();
    ~SayHello();
    static char* Hello();
};

SayHello.cpp :

#include "SayHello.h"
extern "C"
{
    SayHello::SayHello(){}

    SayHello::~SayHello(){}

    char * SayHello::Hello()
    {
        return "Hello !";
    }
}

Then I generated a file libSayHello.so and created a project Android with xamarin to try to call the function hello. There is my MainActivity.cs :

[DllImport("libSayHello.so")]
static extern String Hello();

protected override void OnCreate(Bundle bundle)
{
    // I paste only my added code :
    String hello = Hello();
    Toast.MakeText(this.ApplicationContext, hello, ToastLength.Long);
}

I did all steps in this tutorial, but I have an exception :

System.DllNotFoundException: libSayHello.so

I searched for this, but I must be so noob cause I did not find anything. How should I use my libSayHello.so ?

EDIT:

There is my libSayHello.so seen with 7zip:

enter image description here

And my project :

enter image description here

like image 904
A.Pissicat Avatar asked Sep 22 '17 12:09

A.Pissicat


1 Answers

I think this will be the best sample for you.

This all works according to the following scheme:

  1. Android supports 7 CPU architectures.

    But Xamarin supports 5 of them. So in the settings of your Xamarin.Android project check which architectures you will support:

    [Xamarin.Droid.project]->[Properties]->[Android Options]->[Advanced]->[Supported architectures]

enter image description here

Check which archs are necessary for your project. According to this your shared library should be compiled for these archs. And you should put your shared libraries in Xamarin.Droid.project's folder lib:

enter image description here

  1. To see them in Solution Explorer you should mention them in your Xamarin.Android project's .CSPROJ.

    Add there next item groups:

    <ItemGroup> <AndroidNativeLibrary Include="lib\{ARCH}\libCLib.so"> <Abi>{ARCH}</Abi> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </AndroidNativeLibrary> </ItemGroup>

    {ARCH} could be next: armeabi, armeabi-v7a, arm64-v8a, x86, x86_64.

  2. Now you can put DllImport in your code:

    [DllImport("libCLib", EntryPoint = "clib_add")]
    public static extern int Add(int left, int right);
    

    I think you have to tell about entry point, because i had runtime errors without this statement System.EntryPointNotFoundException.

    And don't forget to add next in your code:

    using System.Runtime.InteropServices;

like image 110
Sheikh Avatar answered Oct 24 '22 13:10

Sheikh