I am developing a AAR plugin for my Unity application.
I would like to send a string variable from the AAR library to Unity.
How could we do that?
For strings coming back from native, this is the C# interop stub:
[DllImport ("vanilib")]
private static extern System.IntPtr dispatcher1_entrypoint1(int opcode1, int arg1);
for this C method:
char *dispatcher1_entrypoint1( int opcode1, int arg1);
NOTE: It must be an extern "C" { } function, not C++!
And this is the Marshal code to get the string back:
string s = Marshal.PtrToStringAnsi( dispatcher1_entrypoint1( (int)opcode, arg1));
More reading can be had by googling unity android plugin
And some more previous scribblings:
EDIT: To clarify, this system is setup to return strings again and again, and it does so by simply returning the fixed (static) buffer where the zero-terminated C strings have been copied into. This gets me away from any concerns about malloc() / free();
Well, lets just drop this identical SO question here for reference. You have to be careful when interfacing with native code. If you allocate memory for the char* on the native side, when and how do you free that memory? If you read through the answers on the SO question, there’s the BStr type on the C / C++ side where the marshaller can actually handle the deallocation of the memory. Returning just a char pointer won’t do it.
In a lot cases you would actually reverse the data flow like shown in this answer. In fact literally any method of the windows API that returns a string to you requires you to allocate the memory for the string yourself. So you are providing the memory to the API and it just fills that memory with the data you’re requesting. Such methods usually return the number of bytes written, but they don’t have to. In the “GetWindowText” example the API actually has a seperate method to query the length beforehand.
It’s up to you how you want to design your API, but be careful when it comes to allocations. Using managed memory is usually a lot easier.
Thanks for your answers, In my case I am using an AAR plugin done in Java with Android Studio. The solutions you are telling me about are based on C/ C++ plugin. Is it possible to do that also when calling plugin functions done in java?
Have a look at our documentation for AndroidJavaObject and AndroidJavaProxy.