我设法通过使用资源as outlined here 实现了我的目标。
这是我如何使它工作的。 (我是 C++ 新手,如果您发现任何愚蠢之处,请告诉我)
- 将托管代码编译为单个文件
- 将托管代码可执行文件重命名为 .txt
- 创建一个新的 Visual C++ Win32 控制台应用程序
- 添加新项目 - 资源文件 (.rc)
- 打开资源文件,添加资源,选择导入,类型输入“TEXT”
- 修改“DWORD 大小” 以匹配托管 .txt 文件的大小
其余的可以用代码转储来解释。
希望这会帮助某人(像我这样的 C++ 新手......)
#include "stdafx.h"
#include "resource.h"
#include "windows.h"
#include "iostream"
#include <string>
#include <sstream>
using namespace std;
namespace std
{
HRSRC hrsrc = NULL;
HGLOBAL hGlbl = NULL;
BYTE *pExeResource = NULL;
HANDLE hFile = INVALID_HANDLE_VALUE;
DWORD size = 8192; //hardcoding the size of the exe resource (in bytes)
HINSTANCE g_Handle = NULL;
HINSTANCE hInstance = NULL; // Passing NULL uses the instance that started the process( CSMerged.exe ).
template <typename T>
string NumberToString(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
hrsrc = FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_TEXT1), _T("TEXT"));
if (hrsrc == NULL)
{
cout << "hrsc is null! \n";
cin.get(); // leave the console open.
return FALSE;
}
hGlbl = LoadResource(hInstance, hrsrc);
if (hGlbl == NULL)
{
cout << "hGlbl is null! \n";
cin.get(); // leave the console open.
return FALSE;
}
pExeResource = (BYTE*)LockResource(hGlbl);
if (pExeResource == NULL)
{
cout << "pExeResource is null! \n";
cin.get(); // leave the console open.
return FALSE;
}
hFile = CreateFile(L"ManagedCode.exe", GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
DWORD bytesWritten = 0;
WriteFile(hFile, pExeResource, size, &bytesWritten, NULL);
CloseHandle(hFile);
}
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
int ret = CreateProcess(L"ManagedCode.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if (ret == 1) { return 0; } // the process started successfully, so I'm done here.
else
{
cout << "CreatePrecess returns " + NumberToString(ret) + ". \n";
cin.get(); // leave the console open
}
return 0;
}
Resource.h
- 这是自动生成的,以及当我使用 VS2013 的 GUI 导入资源时对 Recource.rc 的修改。
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Resource.rc
//
#define IDR_TEXT1 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
我应该添加一些我必须更改的其他内容才能使其在 Windows XP 上运行:
- 确保平台目标是 Win32
- 将配置属性>常规>平台工具集设置为“Visual Studio 2013 - Windows XP (x120_xp)”
- 将配置属性>C/C++>代码生成>运行时库设置为“多线程(/MT)