是否有可能举办一个C程序的CLR? [英] Is it possible to host the CLR in a C program?
问题描述
每个例子,我能找到的是在C ++中,但我想保持我的项目在C.它甚至有可能主办的CLR在C程序?
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?
推荐答案
由于上述评论暗示,有一组的 COM API,用于承载CLR ,你应该能够从C和C ++。
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++.
作为一个例子,下面是一个快速的一块(未经测试)C code的,显示了如何启动CLR和在托管组件(这需要一个字符串作为参数执行类的静态方法并返回一个整数)。这code和C之间的主要区别++对应的是 COBJMACROS
的定义和使用&LT的;类型> _<方法>
宏(如 ICLRRuntimeHost_Start
)以调入CLR托管COM接口。 (请注意, COBJMACROS
的必须的被的#include
之前定义的ING mscoree.h
,以确保这些工具宏定义得到。)
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 that COBJMACROS
must be defined prior to #include
'ing mscoree.h
to make sure these utility macros get defined.)
#include <windows.h>
#define COBJMACROS
#include <mscoree.h>
int main(int argc, char **argv)
{
HRESULT status;
ICLRRuntimeHost *Host;
BOOL Started;
DWORD Result;
Host = NULL;
Started = FALSE;
status = CorBindToRuntimeEx(
NULL,
NULL,
0,
&CLSID_CLRRuntimeHost,
&IID_ICLRRuntimeHost,
(PVOID *)&Host
);
if (FAILED(status)) {
goto cleanup;
}
status = ICLRRuntimeHost_Start(Host);
if (FAILED(status)) {
goto cleanup;
}
Started = TRUE;
status = ICLRRuntimeHost_ExecuteInDefaultAppDomain(
Host,
L"c:\\path\\to\\assembly.dll",
L"MyNamespace.MyClass",
L"MyMethod",
L"some string argument to MyMethod",
&Result
);
if (FAILED(status)) {
goto cleanup;
}
// inspect Result
// ...
cleanup:
if (Started) {
ICLRRuntimeHost_Stop(Host);
}
if (Host != NULL) {
ICLRRuntimeHost_Release(Host);
}
return SUCCEEDED(status) ? 0 : 1;
}
此样品应与.NET 2.0+工作,尽管它看起来像.NET 4.0(尚未发布),具有德precated一些这些API赞成的 microsoft.com/en-us/library/dd233120%28VS.100%29.aspx\">new的API集。 (如果你需要这个使用.NET 1.x的工作,你需要使用 ICorRuntimeHost 的ICLRRuntimeHost代替。)
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.)
这篇关于是否有可能举办一个C程序的CLR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!