无法加载自定义DLL

时间:2018-02-06 10:45:30

标签: c++ powershell dll

我创建了一个打开cmd.exe的简单DLL。

我用这些选项做到了:
enter image description here enter image description here

在默认dlllmain.cpp中,我添加了一个代码,用于创建新的cmd.exe

// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include <Windows.h>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    {
        STARTUPINFO info = { sizeof(info) };
        PROCESS_INFORMATION processInfo;
        BOOL h = CreateProcessW(L"C:\\Windows\\System32\\cmd.exe", L"", NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo);
    }
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

当我使用控制台应用程序测试时,DLL_PROCESS_ATTACH下方的这三行对我有用。

我希望每个加载此DLL的进程都会打开cmd.exe

我尝试使用PowerShell加载DLL:

Add-Type -TypeDefinition @"
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    public static class Kernel32
    {
        [DllImport("kernel32", SetLastError=true, CharSet = CharSet.Ansi)]
            public static extern IntPtr LoadLibrary(
                [MarshalAs(UnmanagedType.LPStr)]string lpFileName); 
} 


"@

    $LibHandle = [Kernel32]::LoadLibrary("C:\tmp\myDll.dll")

但没有任何反应,$LibHandle的价值是0

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我发现了什么问题。
我的系统是64位,文件是32位编译的 我需要在Visual Studio中指定我在x64位编译它 enter image description here

我没有在开始时检查它,因为我认为当我在“任何CPU”模式下编译时,它会自动将64位文件编译为OS体系结构。

现在它运作正常。