aws-sdk-net: AWS SDK Not Working On Android With Unity 2019.1.0f2

Hello guys. I’m getting the same errors described in #1262 but I’m getting those when trying to call a Lambda function with Amazon.Lambda.AmazonLambdaClient.InvokeAsync.

Just to make clear: this issue is happening in Android builds with Unity 2019.1.0f2. The AWS plugin works fine in the Unity Editor.

Expected Behavior

The callback method passed to Amazon.Lambda.AmazonLambdaClient.InvokeAsync should get called when the response is received.

Current Behavior

The callback method passed to Amazon.Lambda.AmazonLambdaClient.InvokeAsync never gets called and the following errors are thrown:

Error Unity Unable to find /usr/lib/libobjc.dylib
Error Unity ArgumentException: Object of type 'System.Object[]' cannot be converted to type 'UnityEngine.AndroidJavaObject[]'.
Error Unity at System.RuntimeType.CheckValue (System.Object value, System.Reflection.Binder binder, System.Globalization.CultureInfo culture, System.Reflection.BindingFlags invokeAttr) [0x00071] in <a6266edc72ee4a578659208aefcdd5e1>:0 
Error Unity at System.Reflection.MonoMethod.ConvertValues (System.Reflection.Binder binder, System.Object[] args, System.Reflection.ParameterInfo[] pinfo, System.Globalization.CultureInfo culture, System.Reflection.BindingFlags invokeAttr) [0x00069] in <a6266edc72ee4a578659208aefcdd5e1>:0 
Error Unity at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00011] in <a6266edc72ee4a578659208aefcdd5e1>:0 
Error Unity at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <a6266edc72ee4a578659208aefcdd5e1>:0 
Error Unity a

Possible Solution

I’ve submitted a bug report to Unity’s support with an example project and they were able identify the source of the issue. They did some design changes in Unity 2019 that break the AWS plugin code. Bellow is the answer I got from them describing the issue:

Hi!

The error you are seeing is caused by incorrect use of reflection in the AWS plugin: https://github.com/aws/aws-sdk-net/blob/b691e46e57a3e24477e6a5fa2e849da44db7002f/sdk/src/Core/Amazon.Util/Internal/_unity/AndroidInterop.cs#L59

In particular, line 71 (which finds the method) was used to find and call the method with the signature

(1) public ReturnType CallStatic<ReturnType>(string methodName, params object[] args)

In Unity 2019.1, to improve support for passing an array to the methods, we added few new methods to AndroidJavaObject, among them:

(2) public void CallStatic<T>(string methodName, T[] args) (3) public ReturnType CallStatic<ReturnType, T>(string methodName, T[] args)

The plugin wants to find a method which returns AndroidJavaObject (signature (1), see call to MakeGenericMethod()), but now it finds method (2) where T: AndroidJavaObject. This method expects AndroidJavaObject[] as a param, but it gets object[] so you get your error.

The fix for the issue should be done on AWS SDK side, by updating the LINQ query to find the method. Please submit a bug report on Github, feel free to include the info I posted here.

I’m closing this bug as “By design”.

Regards Yury Habets

Can anyone please verify (and hopefully fix) this? Thanks in advance.

Steps to Reproduce (for bugs)

Just call Amazon.Lambda.AmazonLambdaClient.InvokeAsync and you see that the callback never gets called and some errors are thrown. Actually, this issue affects all async methods in the SDK, another example would be Amazon.S3.AmazonS3Client.ListObjectsAsync.

Context

Below is the only script I’ve included in the example project I submitted to Unity:

using System.Text;
using Amazon;
using Amazon.Lambda;
using Amazon.Lambda.Model;
using UnityEngine;
using UnityEngine.UI;

public class AmazonLambdaFunctionInvoker : MonoBehaviour {
    [SerializeField] string region;
    [SerializeField] string functionName;
    [SerializeField] string functionPayload;
    [SerializeField] string accessKey;
    [SerializeField] string secretKey;

    [SerializeField] Text logText;
	
    void Awake() {
        logText.text = string.Format("[ Built with Unity {0} ]\n\n", Application.unityVersion);

	UnityInitializer.AttachToGameObject(gameObject);
	logText.text += "AWS Plugin Initialized.\n";

	AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest;
	logText.text += "AWS HTTP Client set to UnityWebRequest.\n";
    }

    void Start() {
	AmazonLambdaClient client = new AmazonLambdaClient(accessKey, secretKey, RegionEndpoint.GetBySystemName(region));
		
        using (client) {
            logText.text += string.Format("Invoking {0}('{1}')...\n", functionName, functionPayload);
			
	    client.InvokeAsync(new InvokeRequest() { FunctionName = functionName, Payload = functionPayload }, (responseObject) => {
		logText.text += "Lambda response received.\n";
				
		if (responseObject.Exception != null) {
		    logText.text += "ERROR: " + responseObject.Exception.Message + '\n';
		    return;
		}

		float result;
		float.TryParse(Encoding.ASCII.GetString(responseObject.Response.Payload.ToArray()), out result);
				
		logText.text += "Function result: " + result + '\n';	
	    });
        }
    }
}

Your Environment

  • AWSSDK.Core version used: 3.3.500.0
  • Operating System and version: Windows Unity Editor 2019.1.0f2 building app to Android

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 4
  • Comments: 48 (3 by maintainers)

Commits related to this issue

Most upvoted comments

Alright, I got the time to properly fix the issue. I tried a LINQ query based on the link in my previous post. I replaced line 71 of AndroidInterop.cs for this:

var callStaticMethod = androidJavaClassType.GetMethods().Where(x => x.Name == "CallStatic").First(x =>
    x.ContainsGenericParameters &&
    x.GetParameters().Select(y => y.ParameterType).SequenceEqual(new Type[] { typeof(string), typeof(object[]) })
);

I made similar queries for the other lines I mentioned previously and it worked. Now the queries find the method signatures with the specific parameters sequences we want and the queries don’t rely on the returning order anymore because only one method is returned by each query.

I’ll submit a Pull Request.

Still a lot of views about this issue. You may watch this video to solve that step by step: https://youtu.be/uRNUJzQzNTk

Alright, I got the time to properly fix the issue. I tried a LINQ query based on the link in my previous post. I replaced line 71 of AndroidInterop.cs for this:

var callStaticMethod = androidJavaClassType.GetMethods().Where(x => x.Name == "CallStatic").First(x =>
    x.ContainsGenericParameters &&
    x.GetParameters().Select(y => y.ParameterType).SequenceEqual(new Type[] { typeof(string), typeof(object[]) })
);

I made similar queries for the other lines I mentioned previously and it worked. Now the queries find the method signatures with the specific parameters sequences we want and the queries don’t rely on the returning order anymore because only one method is returned by each query.

I’ll submit a Pull Request.

Worked like a charm. Copied AndroidInterop class content from your version at this link: https://github.com/aws/aws-sdk-net/blob/af307ffcd7dd3ba78c2b185bb10e6bf1738ddaaf/sdk/src/Core/Amazon.Util/Internal/_unity/AndroidInterop.cs

Thanks!

I’ve managed to fix the issue. I cloned the repo, opened the AWSSDK.Unity Solution, added the UnityEngine.dll reference through NuGet and fixed the wrong lines in AndroidInterop.cs to finally build the AWSSDK.Lambda.Unity project to get the fixed DLLs. I don’t know if the NuGet referencing method is the right one, I was not able to reference my local UnityEngine.dll.

Here is what I did to fix the code:

As pointed out by Yury (from Unity support), they added new methods to AndroidJavaObject in Unity 2019.1. Before that there was only one possible result for the LINQ query in line 71 of AndroidInterop.cs, which was ReturnType CallStatic<ReturnType>(System.String, System.Object[]), but now the Where() clause of the query returns three methods:

Void CallStatic<T>(System.String, T[])
ReturnType CallStatic<ReturnType,T>(System.String, T[])
ReturnType CallStatic<ReturnType>(System.String, System.Object[])

Those methods are returned in the same order above, so our desired method is no longer accessible by the First() clause in the LINQ query. Our method is now the third and last one, not the first. The same issue also happens in lines 92, 107 and 172.

To fix that I simply replaced the First() clause in the wrong queries for Last(). That doesn’t seem to be a good solution because Unity could add or remove methods in the future and change the returning order of the query again. I think the ultimate solution would be a query to pinpoint the exact method signature we need and don’t rely on the order of the results. I don’t know how to do that, it’s the first time I have to deal with this reflection stuff. I think it’s possible though, let me know how please.

I don’t know what is the process now. Will you guys put that fix on the roadmap?

If the AWS Unity SDK is deprecated it would be great to have the docs updated so that people don’t waste their time with it.

If you can’t build the dll for unity2019 yourself, you may download the dll here: https://lhkmarcus.com/2020/04/05/how-to-use-aws-sdk-in-unity-2019/

@left-brain, I would also be interested in seeing your solution. I tried a few dll’s that I’ve seen posted and I end up getting this error:

E/Unity: TypeLoadException: Could not load type of field 'Amazon.SecurityToken.AmazonSecurityTokenServiceConfig:<StsRegionalEndpoints>k__BackingField' (0) due to: Could not resolve type with token 0100002a (from typeref, class/assembly Amazon.Runtime.StsRegionalEndpointsValue, AWSSDK.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=null) assembly:AWSSDK.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=null type:Amazon.Runtime.StsRegionalEndpointsValue member:(null) signature:<none> at Amazon.CognitoIdentity.CognitoAWSCredentials..ctor (System.String accountId, System.String identityPoolId, System.String unAuthRoleArn, System.String authRoleArn, Amazon.RegionEndpoint region) [0x00017] in <a0afd534d77f4c8ebd0c1d004e7b7b27>:0 at Amazon.CognitoIdentity.CognitoAWSCredentials..ctor (System.String identityPoolId, Amazon.RegionEndpoint region) [0x00000] in <a0afd534d77f4c8ebd0c1d004e7b7b27>:0 at LambdaService.get_Credentials () [0x00015] in <7e7a86cace5a404c9dd13906b7ae2d7a>:0 at LambdaService.get_Clie

I’m assuming this might be because the versions of the sdk and the dll are out of sync? I tried compiling the dll myself by pulling the solution and adding the fix then building the AWSSDK.core.unity project. I get no errors but the dll still won’t show up in the bin folder.

Has anyone tried anything else that worked for them?

IF you need the DLL , here’s it. Just translate the webpage as it is in Korean. http://today7e.blogspot.com/2019/07/unity-android-aws-sdk-unity-2019-error.html

Thanks, I had managed to compile the latest version myself, it works perfectly. I’m just worried about the other users, this is very inconvenient. It looks like sdk is abandoned for Unity, while Firebase Database probably wouldn’t have this problem.

Great, can you please share your solution too, just in case…

It’s not a duplicate. I’ve read the entire report and comments of #1262 and a proper fix was not made, only a workaround was achieved by the OP. And the real source of the issue was never pointed out.

My report shows the exact source of the issue and the possible fix pointed out by Unity’s support team, it is clearly described in the Possible Solution section. Isn’t that correct?