是否可以在 C 程序中托管 CLR?
我能找到的每个示例都是用 C++ 编写的,但我试图将我的项目保留在 C 语言中。是否有可能在 C 程序中托管 CLR?
如果是这样,你能给我举个例子吗?
Every example I can find is in C++, but I'm trying to keep my project in C. Is it even possible to host the CLR in a C program?
If so, can you point me to an example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如上面的评论提示,有一组 COM API 用于托管 CLR,并且您应该能够从 C 和 C++ 调用这些 COM API。
作为示例,下面是一段快速的(未经测试的)C 代码,它展示了如何启动 CLR 并在托管程序集中执行类的静态方法(它接受字符串作为参数并返回整数)。此代码与其 C++ 对应代码之间的主要区别在于
COBJMACROS
的定义以及_
宏的使用(例如ICLRRuntimeHost_Start< /code>) 调用托管 CLR 的 COM 接口。 (请注意,
COBJMACROS
必须在#include
'ingmscoree.h
之前定义,以确保这些实用宏得到定义。)此示例应该与 .NET 2.0+ 一起使用,尽管看起来 .NET 4.0(尚未发布)已经弃用了其中一些 API,转而使用 用于托管 CLR 的新 API 集。 (如果您需要它与 .NET 1.x 一起使用,则需要使用 ICorRuntimeHost 而不是 ICLRRuntimeHost。)
As the above comments hint, there is a set of COM APIs for hosting the CLR, and you should be able to call these COM APIs from both C and C++.
As an example, below is a quick piece of (untested) C code that shows how to start up the CLR and execute a static method of a class in a managed assembly (which takes in a string as an argument and returns an integer). The key difference between this code and its C++ counterpart is the definition of
COBJMACROS
and the use of the<type>_<method>
macros (e.g.ICLRRuntimeHost_Start
) to call into the CLR-hosting COM interface. (Note thatCOBJMACROS
must be defined prior to#include
'ingmscoree.h
to make sure these utility macros get defined.)This sample should work with .NET 2.0+, although it looks like .NET 4.0 (not yet released) has deprecated some of these APIs in favor of a new set of APIs for hosting the CLR. (And if you need this to work with .NET 1.x, you need to use ICorRuntimeHost instead of ICLRRuntimeHost.)