Reputation: 1081
In C# .NET 8 given a pointer (IntPtr) to a native object implementing a COM-compatible interface and a C# interface definition, how do I convert the pointer to an object implementing such interface without using built-in COM to enable trimming?
Background:
I have a small C# app (.NET 8) which uses a COM library via autogenerated bindings from tlb. I would like to publish a standalone exe and use .NET's trimming option <PublishTrimmed>
to make the exe's size reasonable.
The .NET built-in com interop does not support trimming. I have found a subset of dlls to mark not trimmable to make the app run. However, that still generates a lot of warnings and is I believe technically unsupported by .NET and can break in later .NET versions.
The COM DLL doesn't actually require full COM, it just uses COM-compatible API. All I need is to call a P/Invoke method which returns a pointer to a COM-like object, which matches the autogenerated tlb interface. How would I convert that pointer to an object implementing a particular C# COM-compatible interface using only features supported by trimming?
// auto generated from tlb
[ComImport]
[Guid(<guid>)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISomeInterface
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void method([In][MarshalAs(UnmanagedType.LPWStr)] string input, out int pbData);
...
}
// my (simplified) current code using built in com interop
void GetInstance([MarshalAs(UnmanagedType.Interface)] out object createdObject);
GetInstance(out object comObject);
return comObject as ISomeInterface ?? throw new InvalidOperationException("Failed to create ISomeInterface instance.");
Upvotes: 0
Views: 39