0

I'm adding an existing Xamarin.Android .NET library to a native Android Studio project. I'm following the indications on https://learn.microsoft.com/en-us/xamarin/tools/dotnet-embedding/ and everything works well, but I have a question not being a Java expert: is it also possible to export to Java the C#'s properties and actions present in my libraries (like ReturnAnyText)?

namespace export_test
{
    [Register("export_test.ClassToExport")]
    public class ClassToExport 
    {
        [Export("ClassToExport")]
        public ClassToExport()
        {
            // ...
        }

        [Export("DoSomething")]
        public void DoSomething()
        {
            // ...
        }

        public Action<string> ReturnAnyText { get; set;}
    }
}
AndreaGobs
  • 338
  • 2
  • 18

2 Answers2

0

A property under the hood are just get_PropertyName() and set_PropertyName() methods. So yes, you should be able to export those too:

This would look something like:

public bool MyProp
{
    [Export]
    get;
    [Export]
    set;
}

Or if you want to name them:

public bool MyProp
{
    [Export("GetMyProp")]
    get;
    [Export("SetMyProp")]
    set;
}
Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
  • Yes for the properties it works. Now the main question is about actions – AndreaGobs Mar 21 '19 at 14:10
  • Not sure I follow. Do you say that it behaves differently for some certain types? Your action is a property... – Cheesebaron Mar 21 '19 at 14:13
  • Yes sorry, I explain better. I have a property with an action as value. With your tip I tried to export a property of an int value and it works, but I'm not able, and I don't know if it possibile, to export also a delegate as value (I read that since Java 8 something similar to C#'s delegates exists in Java, [Java equivalent of C#'s delegates](https://stackoverflow.com/questions/39346343/java-equivalent-of-c-sharp-delegates-queues-methods-of-various-classes-to-be-ex)) – AndreaGobs Mar 21 '19 at 15:34
0

The simplest solution I found is to not try to export C# delegates, and simply return an object containing the return values at the end of the method execution:

namespace export_test
{
    [Register("export_test.ClassToExport")]
    public class ClassToExport 
    {
        [Export("ClassToExport")]
        public ClassToExport()
        {
            // ...
        }

        [Export("DoSomething")]
        public MyResult DoSomething()
        {
            // ...
        }
    }

    [Register("export_test.MyResult")]
    public class MyResult
    {
        private string _Text;
        private int _Value;

        [Export("MyResult")]
        public MyResult(string text, int val)
        {
            _Text = text;
            _Value = val;
        }

        [Export("GetText")]
        public string GetText() { return _Text; }

        [Export("GetValue")]
        public int GetValue() { return _Value; }
    }
}
AndreaGobs
  • 338
  • 2
  • 18