以C++的方式使用C#

起因

之前公司的老大哥高级项目中用到了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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值