c# - 通过反射从 C# 访问 C++ 非成员函数

标签 c# c++ reflection clr non-member-functions

我需要获得有关 C++ 程序的一些运行时信息,这有点困难,因为 C++ 不提供一些复杂的反射机制。现在,我的方法是使用/clr 编译 C++ 代码并反射(reflect) 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 类型数组包含 HelloWorld 类(或者至少我假设它是那个类)时,main var 包含三种类型,所有这些类型都处理 doMAIN(即与 sc_main 无关)我正在寻找的方法)。我假设它与它不公开有关,但是将它声明为 HelloWorld 类的静态公共(public)成员函数也不起作用,因为该函数预计是一个非成员函数。或者我只是忽略了一些非常愚蠢的事情?

最佳答案

不,它没有。您需要了解 C++/CLI 的工作原理——您不能只使用/CLR 重新编译 C++ 程序就完事了。这里的sc_main方法是native的,不是managed的,你无法对其进行反射(reflection),HelloWorld类型也是如此,除非你重新定义为一个ref类,但我怀疑你这样做了,因为你在 main 中按值实例化了它,这只有在它是 native 类时才合法。

.NET 和 native 代码具有截然不同的语义,神奇的编译器开关不会在这方面帮助您。

关于c# - 通过反射从 C# 访问 C++ 非成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6993840/

相关文章:

c# - SQL 字符和 C# 之间的转换

c# - 如何使用泛型测试 NaN(或者为什么 NaN.Equals(NaN) == true)?

c++ - C 中的 Bsearch 函数问题

java - 使用反射和 ClassLoaders 创建类的实例时出现 ClassCastException

java - 我可以覆盖 Java 中的私有(private)方法吗?

c# - 实现 |比较中的运算符

c# - 将对象转换为十进制? (可为空的十进制)

c++ - 操作系统 : Symbols not found for architecture i386

c++ - 关于long long和long double

java - C# 从类型创建类的实例