Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't load custom DLL

I created a simple DLL that open cmd.exe.

I did it with these options:
enter image description here enter image description here

In the default dlllmain.cpp I added a code that creates a new 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;
}

These three lines below the DLL_PROCESS_ATTACH worked for me when I tested it with a console application.

I am expecting that every process that will load this DLL will open cmd.exe.

I tried to load the DLL with PowerShell:

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")

But nothing happens, the value of the $LibHandle was 0.

What I am doing wrong ?

like image 281
E235 Avatar asked Jan 23 '26 00:01

E235


1 Answers

I found what was the problem.
My system is 64 bit and the file was compiled in 32 bit.
I needed to specify in Visual Studio that I am compiling it in x64 bit.
enter image description here

I didn't check it in the beginning because I thought that when I am compiling it on "Any CPU" mode, it compile the file in 64 bit automatically as the OS architecture.

Now it works fine.

like image 84
E235 Avatar answered Jan 24 '26 19:01

E235



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!