起因
之前公司的老大哥高级项目中用到了c#,之后相互嘲笑了一下。后来想到c#中有提供了很多的成员方法,所以好奇c#这种JIT编译的是不是每一个对象的成员函数的地址都是一样的,但是我又不会c#,所以东拼西凑写了一个C#版本的C++demo。
编译时候又几个要注意的点:
1.vc++目录=>引用目录加入==>C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0
2.c++ ==> 常规==>公共语言运行时支持:公共语言运行时支持/clr
3.c++ ==> 语言==>符合模式==>否
4.c++ ==> 代码生成==>启动c++异常==>否
#include <iostream>
#include <windows.h>
#include <vcclr.h>
#using <mscorlib.dll>
#using <System.dll>
#using <System.Management.Automation.dll>
using namespace System;
using namespace System::Management::Automation;
using namespace System::Reflection;
using namespace System::Runtime::InteropServices;
void RunPowerShell(LPCWSTR s)
{
PowerShell::Create()->AddScript(gcnew String(s))->Invoke();
}
int getMemory(System::Object^ obj)
{
GCHandle handle = GCHandle::Alloc(obj, GCHandleType::WeakTrackResurrection);
IntPtr addr = GCHandle::ToIntPtr(handle);
return addr.ToInt32();
}
void Run(int index, PowerShell^ powershell, int objAddress)
{
Type^ test = powershell->GetType();
array<System::Reflection::MethodInfo^>^ methods = test->GetMethods(BindingFlags::Public | BindingFlags::NonPublic | BindingFlags::Instance);
for (int i = 0; i < methods->Length; i++)
{
try
{
printf("index:%d objAddress:0x%x function:%s address:0x%x\n", index, objAddress, methods[i]->Name, methods[i]->MethodHandle.GetFunctionPointer());
}
catch (...) {}
}
}
int main()
{
for (int i = 0; i < 3; i++)
{
PowerShell^ powershell = PowerShell::Create();
Run(i, powershell, *(int*)getMemory(powershell));
}
// RunPowerShell(L"Invoke-WmiMethod -Path win32_process -Name create -ArgumentList notepad.exe");
system("pause");
return 0;
}