'.NET Core: COM delegate throws System.AccessViolationException when trying to call 32-bit dllhost from 64-bit application
I need to pass a delegate function between .NET 6 32.bit COM server and .NET 6 64.bit client to communicate. I wrote a sample with a 32-bit server, implemented as a C# class in a class library project, hosted by Windows system surrogate and a 64-bit client that calls the server.
Class code:
namespace OutOfProcCOM;
[ComVisible(true)]
[Guid(Contract.Constants.ServerInterface)] //F586D6F4-AF37-441E-80A6-3D33D977882D
public interface IServer
{
double Test();
void TestEvent([MarshalAs(UnmanagedType.FunctionPtr)] ChangeDelegate d);
}
[ComVisible(true)]
[Guid(Contract.Constants.ServerInterface)] //F586D6F4-AF37-441E-80A6-3D33D977882D
public delegate bool ChangeDelegate();
[ComVisible(true)]
[Guid(Contract.Constants.ServerClass)] //"AF080472-F173-4D9D-8BE7-435776617347"
public sealed class DllServer : IServer
{
public event OnMyEventDelegate OnMyEvent;
public double Test()
{
return 10;
}
public void TestEvent([MarshalAs(UnmanagedType.FunctionPtr)] ChangeDelegate d)
{
d?.Invoke();
}
}
This is how I register it:
regsvr32.exe "DllServer.comhost.dll"
Registry entry
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Wow6432Node\AppID\{AF080472-F173-4D9D-8BE7-435776617347}]
"DllSurrogate"=""
[HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{AF080472-F173-4D9D-8BE7-435776617347}]
"AppID"="{AF080472-F173-4D9D-8BE7-435776617347}"
And here is the client:
var type = Type.GetTypeFromProgID("OutOfProcCOM.DllServer");
var obj = (IServer)Activator.CreateInstance(type);
var x = obj.Test();
obj.TestEvent(() => {
Console.WriteLine("Hello!");
});
Execution of obj.Test() is working. Execution of obj.TestEvent(...) throws a System.AccessViolationException:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
Is there someone who can help me? I am going crazy migrating a COM application to .NET Core!
Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
