读取字符串实习池的内容 [英] Read the content of the string intern pool
问题描述
我想枚举字符串实习池中的字符串.
也就是说,我想得到string
的所有实例s
的列表,使得:
That is to say, I want to get the list of all the instances s
of string
such that:
string.IsInterned(s) != null
有没有人知道这是否可能?
Does anyone know if it's possible?
推荐答案
感谢@HansPassant 的建议,我设法获得了程序集中的字符串文字列表.这与我最初想要的非常接近.
您需要使用读取程序集元数据,并枚举用户字符串.这可以通过IMetaDataImport
的这三个方法来完成:
You need to use read assembly meta-data, and enumerate user-strings. This can be done with these three methods of IMetaDataImport
:
[ComImport, Guid("7DAC8207-D3AE-4C75-9B67-92801A497D44")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IMetaDataImport
{
void CloseEnum(IntPtr hEnum);
uint GetUserString(uint stk, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] char[] szString, uint cchString, out uint pchString);
uint EnumUserStrings(ref IntPtr phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]uint[] rStrings, uint cmax, out uint pcStrings);
// interface also contains 62 irrelevant methods
}
要获取IMetaDataImport
的实例,需要获取一个IMetaDataDispenser
:
To get the instance of IMetaDataImport
, you need to get a IMetaDataDispenser
:
[ComImport, Guid("809C652E-7396-11D2-9771-00A0C9B4D50C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[CoClass(typeof(CorMetaDataDispenser))]
interface IMetaDataDispenser
{
uint OpenScope([MarshalAs(UnmanagedType.LPWStr)]string szScope, uint dwOpenFlags, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIUnk);
// interface also contains 2 irrelevant methods
}
[ComImport, Guid("E5CB7A31-7512-11D2-89CE-0080C792E5D8")]
class CorMetaDataDispenser
{
}
这是怎么回事:
var dispenser = new IMetaDataDispenser();
var metaDataImportGuid = new Guid("7DAC8207-D3AE-4C75-9B67-92801A497D44");
object scope;
var hr = dispenser.OpenScope(location, 0, ref metaDataImportGuid, out scope);
metaDataImport = (IMetaDataImport)scope;
其中 location
是程序集文件的路径.
where location
is the path to the assembly file.
之后,调用 EnumUserStrings()
和 GetUserString()
是直接的.
After that, calling EnumUserStrings()
and GetUserString()
is straighforward.
这是一篇包含更多细节的博文,以及GitHub 上的演示项目.
这篇关于读取字符串实习池的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!