问题
I need to gain some run-time information about a C++ program, which is kinda difficult due to C++ not offering some sophisticated reflection mechanism. Now, my approach is to compile the C++ code using /clr and to reflect over the resulting assembly from C# (simply because I like that language more than C++).
While this is all turning out more or less fine, I'm now stuck at a point where I need to actually run the program by calling its main method. Which is kind of frustrating considering how far I got already...
This is the C++ program in question:
#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);
}
Nothing fancy, really...
This is the C# method used to inspect the resulting assembly:
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();
Now, while the hello Type-array contains the HelloWorld class (or at least I assume that it is that class), the main var contains three types, all of which deal with doMAINs (ie have nothing to do with the sc_main method I'm looking for). I assume that it has something to do with it not being public, but declaring it a static public member function of the HelloWorld class doesn't work either since the function is expected to be a non-member function to be found. Or am I just overlooking something terribly stupid?
回答1:
No, it doesn't. You need to learn how C++/CLI works- you can't just recompile a C++ program with /CLR and be done with it. The sc_main
method here is native, not managed, and you can't reflect over it, and the same is true about the HelloWorld type, unless you redefined it to be a ref class
, but I doubt you did because there you go in main instantiating it by value, which would only be legal if it was a native class.
.NET and native code have very fundamentally different semantics and a magic compiler switch will not help you in this regard.
来源:https://stackoverflow.com/questions/6993840/accessing-a-c-non-member-function-from-c-sharp-via-reflection