I am a beginner in AOT. Recently I followed a tutorial to try it.
Here is the code of the tutorial:
using System.Runtime.InteropServices;
namespace ClassLibrary1
{
public class Class1
{
[UnmanagedCallersOnly(EntryPoint = "Add")]
public static int Add(int a, int b) => a + b;
}
}
And it runs well.
Now I want to return a string and I code it like this:
[UnmanagedCallersOnly(EntryPoint = "Test")]
public static string Test()
{
return "Test";
}
Then VS reports an error:
Cannot use ‘string’ as a return type on a method attributed with
‘UnmanagedCallersOnly’.
What’s wrong with it? How can I return a string in Native AOT?
4
Because the method will be called from unmanaged code, which cannot directly handle managed types like string, the [UnmanagedCallersOnly] attribute in Native AOT can only be applied to methods that use simple data types like integers or pointers, which is the cause of the problem you are experiencing.
You need to ensure that memory is managed appropriately and return a pointer to a string in order to retrieve a string from an unmanaged function. When collaborating with unmanaged code, a typical method is to utilize IntPtr or char*. Here’s a quick tutorial on using Marshal to return a string.The managed string can be changed to an unmanaged one using StringToHGlobalAnsi:
using System;
using System.Runtime.InteropServices;
namespace ClassLibrary1
{
public class Class1
{
[UnmanagedCallersOnly(EntryPoint = "Test")]
public static IntPtr Test()
{
string managedString = "Test";
// Convert the managed string to an unmanaged pointer
IntPtr unmanagedString = Marshal.StringToHGlobalAnsi(managedString);
return unmanagedString;
}
}
}
5