【发布时间】:2017-04-01 03:53:56
【问题描述】:
我有一个名为“MyCpp.cpp”的 C++ 源代码,它位于:C:\MyCpp.cpp
...
5 string CplusplusWarningFunction()
6 {
7 int a = 69;
8 int b = a + 1;
9 a = b;
10 b = 69;
11 return "42 is the answer";
12 }
...
现在我想写一个这样的C#函数
void CodeAnalyzer()
{
string path = @"C:\MyCpp.cpp";
int line = 11;
IEnumerable<string> loc = File.ReadLines(path);
string code = loc.ElementAt(line-1);//Yes, it is 'return "42 is the answer";', good job!
string functionFullName = "???";//This suppose to be the string 'CplusplusWarningFunction()', but How to do it???
MessageBox.Show(string.Format("The code {0} at line {1} is in function {2}",code,line,functionFullName));
}
如何获取函数名来替换字符串“???”在上面的 C# 代码中?
我知道这可以做到,因为 MS 的 FxCop 可以做到,有点(FxCop 分析编译的目标代码,而不是原始源代码)。好吧,如果编译的目标代码可以完成,为什么不是原始源代码。
而Visual Studio可以像下图那样做,我希望有一种方法可以访问Visual Studio API:
感谢阅读。
【问题讨论】:
-
loc.ElementAt(5) ?或 4 - 当你调用它时不确定它是否从零开始
-
解析 C++ 比解析 C# 难很多。 (事实上,C# 的设计目标之一是创建一种更容易被工具解析的常规语言。)我强烈建议您考虑使用类似 LLVM 项目的东西来添加钩子,以便为 C++ 添加合适的钩子编译器。另请注意,FxCop 是一个多人年的项目 - 这不是一个学生可以在几个月内完成的事情。
-
@mmcrae 我认为这个想法是 OP 希望它适用于不同的代码文件和不同的行号。
-
其实我有几个理想,你看,在Visual Studio中,当你把你的插入符号放在C++源代码中时,Visual Studio给你函数名,我想一定有办法像 Visual Studio 一样获取函数名称。
-
或者像 Pvs studio viva64 一样,也许我们可以创建一个扩展,这样我们就可以访问 Visual Studio API。
标签: c# c++ text static analysis