13

I made two simple functions (set and return an int) on eclipse (Android project) in C. I used ndk-build to produce a .so. How can i use this .so on Xamarin and consume those two functions on my Xamarin.Android project?

Thanks!

1 Answers1

15

Let’s assume we have a shared library called MyTest.so and we want to use it in the Xamarin.Android project. The MyTest.so consists of a function

int MyTest_GetValue();

Now, we need to use this function on Xamarin.Android project. Here are the steps so as to succeed:

Step 1: Create a new folder inside the Xamarin.Android project called lib and sub-folder armeabi. Copied my .so library to be used inside the armeabi folder as stated here

Step 2: Set the properties of the library.so (imported library) Build action to "AndroidNativeLibrary" and Copy to output to "Always Copy".

Step 3: (Working in Xamarin.Android Class eg: MainActivity.cs)

  • Include the namespace InteropServices by “using System.Runtime.InteropServices;”

  • Use the standard DllImport in the project to import the native library as below:

    [DllImport("MyTest.so")] 
    public extern static int MyTest_GetValue();// with exact Functtion Name, Type & Params in the .so Lib.
    

Step 4: Consume the function above (MyTest_GetValue()) in the application.

For Example:

int value= MyTest_GetValue();

Console.Writeline(value.ToString());

Mission Accomplished! :D

Tim Sylvester
  • 22,897
  • 2
  • 80
  • 94
  • Can you show an example function with an [out] argument? Like bool MyTest_GetValue(string* retVal); Thanks – hrz Jun 29 '16 at 06:30
  • As far as i can think of, it should not be any different using [out] arguments. Performing steps 1 &2, then step 3 that includes function with [out] arguments and finally step 4 for consuming that function should work fine. Note: Xamarin has changed a lot since 2013 (this question). –  Jun 30 '16 at 19:51