I am trying to call Native AOT library published with –
dotnet publish -r win-x64 -c Release
from managed C# class method (Debug – Any CPU).
I am getting below error –
System.AccessViolationException: ‘Attempted to read or write protected memory. This is often an indication that other memory is corrupt.’
Below is my Code –
Native Lib –
`using System;
using System.Data;
using System.Runtime.InteropServices;
public class NativeExports
{
[UnmanagedCallersOnly(EntryPoint = "multiply")]
public static IntPtr multiply(int a, int b)
{
DataTable table = new DataTable();
IntPtr ptr;
try
{
table.Columns.Add("Value");
table.Rows.Add(a*b);
GCHandle gch = GCHandle.Alloc(table);
ptr = GCHandle.ToIntPtr(gch);
return ptr;
}
catch
{
// TODO this function has no way to propagate errors
table.Rows.Add(-1);
GCHandle gch = GCHandle.Alloc(table);
ptr = GCHandle.ToIntPtr(gch);
return ptr;
}
}
}
`
C# Caller –
`…
using System;
using System.Data;
using System.IO;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
static class MulCsPinvoke
{
[DllImport("mul")]
static extern IntPtr multiply(int a, int b);
public static void Main()
{
DataTable table = new DataTable();
var c = multiply(7, 6);
GCHandle gch = GCHandle.FromIntPtr(c);
Object tw = gch.Target;
//error at below line , unable to read tw
table = (DataTable)tw;
Marshal.FreeHGlobal(c);
}
}
…`
I was expecting memory pointer back . And using target of GCHandle I am trying to cast memory back to DataTable.
Thanks in Advance !