日期:2014-05-18  浏览次数:20952 次

[疑问]用C#以非托管方式被调用之后,如何访问他宿主(C++)的全局变量
我用C#写了一个DLL 用C++调用,,然后 想在 C#里使用C++里定义的全局变量..不如是否有法..!

------解决方案--------------------
可以!
使用C++调用托管的代码,可以使用CLR via C#里边现成的例子,代码如下:
#include <Windows.h>
#include <MSCorEE.h>
#include <stdio.h>
void main(int argc, WCHAR **argv) {
// Load the CLR
ICLRRuntimeHost *pClrHost;
HRESULT hr = CorBindToRuntimeEx(
NULL, // desired CLR version (NULL=latest)
NULL, // desired GC flavor (NULL=workstation)
0, // desired startup flags
CLSID_CLRRuntimeHost, // CLSID of CLR
IID_ICLRRuntimeHost, // IID of ICLRRuntimeHost
(PVOID*) &pClrHost); // returned COM interface
// (This is where you would set Host managers)
// (This is where you could get CLR managers)
// Initialize and start the CLR
pClrHost->Start();
// Load an assembly and call a static method that
// takes a String and returns an Int32
DWORD retVal;
hr = pClrHost->ExecuteInDefaultAppDomain(
L"SomeMgdAssem.dll",
L"Wintellect.SomeType", L"SomeMethod", L"Jeff", &retVal);
// Show the result returned from managed code
wprintf(L"Managed code returned %d", retVal);
// Terminate this process (destroying the CLR loaded in it)
}
你在使用的时候,只要把c++里边的全局变量传到调用方法里边就可以了。
MSDN里边应该有详细的说明。