Skip to content

Instantly share code, notes, and snippets.

@devhawk
Created June 11, 2012 18:07
Show Gist options
  • Save devhawk/2911677 to your computer and use it in GitHub Desktop.
Save devhawk/2911677 to your computer and use it in GitHub Desktop.
P/Invoke and wrapper method for RoResolveNamespace
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
class WinRTInterop
{
public class ResolvedNamespaces
{
public string[] MetadataFilePaths;
public string[] SubNamespaces;
}
public static ResolvedNamespaces ResolveNamespace(string namespaceName, string windowsMetadataDir = null, string[] packageGraphDirs = null)
{
UInt32 tempPathsCount, tempNamespacesCount;
IntPtr[] tempPaths = null;
IntPtr[] tempNamespaces = null;
IntPtr[] tempPackageGraphDirs = null;
try
{
if (packageGraphDirs != null)
{
tempPackageGraphDirs = packageGraphDirs.Select(dir => WindowsRuntimeMarshal.StringToHString(dir)).ToArray();
}
var hr = RoResolveNamespace(
namespaceName,
String.IsNullOrEmpty(windowsMetadataDir) ? string.Empty : windowsMetadataDir,
tempPackageGraphDirs == null ? 0 : (uint)tempPackageGraphDirs.Length,
tempPackageGraphDirs,
out tempPathsCount, out tempPaths, out tempNamespacesCount, out tempNamespaces);
var metadataFilePaths = tempPathsCount == 0 ? new string[0] : tempPaths.Select(p => WindowsRuntimeMarshal.PtrToStringHString(p)).ToArray();
var subNamespaces = tempNamespacesCount == 0 ? new string[0] : tempNamespaces.Select(ns => WindowsRuntimeMarshal.PtrToStringHString(ns)).ToArray();
return new ResolvedNamespaces
{
MetadataFilePaths = metadataFilePaths,
SubNamespaces = subNamespaces,
};
}
finally
{
Action<IntPtr[]> FreeHStrings = ipar =>
{
if (ipar != null)
{
foreach (var hstr in ipar) { WindowsRuntimeMarshal.FreeHString(hstr); }
}
};
FreeHStrings(tempNamespaces);
FreeHStrings(tempPackageGraphDirs);
FreeHStrings(tempPaths);
}
}
[DllImport("WinTypes.dll")]
static extern UInt32 RoResolveNamespace(
[MarshalAs(UnmanagedType.HString)] string name,
[MarshalAs(UnmanagedType.HString)] string windowsMetaDataDir,
UInt32 packageGraphDirsCount,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] packageGraphDirs,
out UInt32 metaDataFilePathsCount,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] out IntPtr[] metaDataFilePaths,
out UInt32 subNamespacesCount,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)] out IntPtr[] subNamespaces);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment