Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COM Interop in Mono 2.0

I am trying to use this code in a Unity project, but it seems the implementations of COM Interop in Mono/.NET differs, which causes the code to fail or crash. Running the code in .NET works fine, but running it with Mono 2.0 (outside of Unity) fails in the same way as in Unity, suggesting it is a problem with Mono in general and not Unity.

If I compile and run the code as-is, it fails because the type cast from MMDeviceEnumerator to IIMMDeviceEnumerator fails. When decorating all interfaces with [ComInterop], the cast succeeds, but the call to GetDefaultAudioEndpoint crashes Unity/Mono with an Access Violation.

It is hard to find good documentation of COM Interop on Mono in general - and particularly so regarding such an old version. Is it at all possible to get this running?

like image 756
Johan Avatar asked Feb 14 '17 10:02

Johan


1 Answers

Wrap the COM functions in C funtions and call the C functions via P/Invoke instead. This can be done in two steps:

  1. Create a VC++ project that wraps the functions you needed in wasapi. Expose them via a module define file or __declspec(dllexport). Build the code into a dll that exposes the functions you need.
  2. In your Unity3D project, access them via P/Invoke.

Here is an example. In your case, just use the COM code in the C/C++ part to do what you want.

like image 81
zwcloud Avatar answered Nov 04 '22 11:11

zwcloud