1

我需要获得一些关于 C++ 程序的运行时信息,这有点困难,因为 C++ 没有提供一些复杂的反射机制。现在,我的方法是使用 /clr 编译 C++ 代码并反映 C# 生成的程序集(仅仅是因为我更喜欢该语言而不是 C++)。

虽然这一切或多或少都很好,但我现在陷入了需要通过调用其 main 方法来实际运行程序的地步。考虑到我已经走了多远,这有点令人沮丧......

这是有问题的 C++ 程序:

#include "systemc.h"
#include <iostream>
using namespace std;

// Hello_world is module name
SC_MODULE (HelloWorld) {
    SC_CTOR (HelloWorld) {
        // Nothing in constructor 
    }
    void HelloWorld::say_hello() {
        //Print "Hello World" to the console.
        cout << "Hello World.\n";
    }
};

//sc_main in top level function like in C++ main
int sc_main(int argc, char* argv[]) {
  HelloWorld hello("HELLO");
  hello.say_hello();
  string input = "";
  getline(cin, input);
  return(0);
}

没什么好看的,真的……

这是用于检查生成的程序集的 C# 方法:

System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(filename);

System.Console.WriteLine(filename + " is an assembly and has been properly loaded.");

Type[] hello = ass.GetTypes().Where(type => type.Name.ToLower().Contains("hello")).ToArray();
Type[] main = ass.GetTypes().Where(type => type.Name.ToLower().Contains("main")).ToArray();

现在,虽然 hello Type-array 包含 HelloWorld 类(或者至少我假设它是那个类),但 main var 包含三种类型,所有这些类型都处理 doMAIN(即与我的 sc_main 方法无关)米找)。我认为它与它不是公共的有关,但是将其声明为 HelloWorld 类的静态公共成员函数也不起作用,因为该函数预计是要找到的非成员函数。还是我只是忽略了一些非常愚蠢的事情?

4

1 回答 1

3

不,它没有。您需要了解 C++/CLI 的工作原理——您不能只使用 /CLR 重新编译 C++ 程序并完成它。这里的sc_main方法是本机的,不是托管的,您无法对其进行反思,对于 HelloWorld 类型也是如此,除非您将其重新定义为 a ref class,但我怀疑您是否这样做了,因为您在那里通过 main 实例化它值,仅当它是本地类时才合法。

.NET 和本机代码具有根本不同的语义,而神奇的编译器开关在这方面对您没有帮助。

于 2011-08-09T09:27:09.910 回答