Running C++ DLL with rundll32 - Missing entry - c++

So I'm trying to use rundll to test and run my C++ written DLL , and i've followed the guidelines here and on other sites and the entry point looks like this:
__declspec(dllexport) void CALLBACK entry(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
{
//do stuff
}
But the rundll process prompts me with an error message box saying "Error in C:\path\to\DLL Missing entry: entry"
Attempted execution command: "rundll32 C:\path\to\DLL, entry".

You can double-check by running Dumpbin.exe /exports on your DLL to see the actual exported name. Which right now is not entry, as the error message tells you.
You need to prefix extern "C" to the declaration to disable C++ name mangling.
Good enough for a 64-bit executable, but that turns it into _entry#16 if this is a 32-bit DLL, still not quite good enough to keep rundll32 happy. Use Project + Add New Item, Code node, pick the "Module-Definition File (.def)" item template. And make it look like this:
EXPORTS
entry = entry

Related

C++ alias for global namespace

I use Visual Studio to create programs in C++ for Windows. I wonder what the best method is to write Windows API functions (including macros) as if they were part of a namespace, e.g. WinAPI. I used to define a macro that is empty, so the preprocessor deletes it, and only the :: will stay in the code, which means global scope:
#define WinAPI
BOOL bResult = WinAPI::SetWindowText( hwnd, L"Test Text" );
// After preprocessing:
BOOL bResult = ::SetWindowText( hwnd, L"Test Text" );
However, I ran into problems with macros, like ListBox_AddString; moreover I don't think that my solution was neat.
I would like to see at first glance whether a function call is part of Windows API, or one of my functions with a similar name. Is there a solution which uses namespaces somehow instead of an empty macro?
Update
I tried to implement Richard Hodges' proposal (using Visual Studio 2010):
namespace MyNamespace
{
int APIENTRY wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR szCmdLine, int iShowCmd )
//...
}
First I received LNK1561: entry point must be defined, so I set Project Properties > Linker > Linker > Advanced > Entry Point = MyNamespace::wWinMain
Then I received LNK1221: a subsystem can't be inferred and must be defined, so I set Project Properties > Linker > Linker > System > SubSystem = Windows (/SUBSYSTEM:WINDOWS)
Now it compiles, links and runs, but iShowCmd is 0x7efde000 (a value I cannot interpret) instead of the usual (SW_SHOW = 0x00000001).
What is wrong?
I think you'll find that it's more productive to put all your application's classes and functions in an app namespace, and treat the global namespace as belonging to the 'current system environment'.
The global namespace is always already polluted with c libraries, windows, posix, OSX, etc.
You can't avoid that, since there are no operating systems with only a c++ API.

How do i write and call this type

I'm having a problem here and the problem is that the hService is 0
I'm having or creating the Windows Form application and I've put:
HSERVICE hService=0;
BOOL fSuccess=EXIT_SUCCESS;
if(Wfs_Startup())
{
// This returns a successful startup even if I write something here
// to be displayed by a textbox it does. That means the Startup is ok.
if(Wfs_Open(&hService))
{
// What ever I put here doesn't show on a textbox and the application jumps to
// the exception of this block which means there's a problem here, at first I
// thought it was because of no corresponding logical name on a registry but what
// I found out was that if I check below the Startup block and check the hService
// it's 0 so it doesn't receive the correct data from the startup.
}
}
so I took that from "I will say" a function that is written like this:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdDLine,
int nShowCmd)
{
//THE CODE BLOCK IS THE SAME AS THE ABOVE THAT GOES HERE.
}
So I took the inside code block to FormLoad but this is giving me the above mentioned problem, can I have both the FormLoad and the WinMain? Because I tried to have the WinMain but there was an error I think it said there can't be two Main or something like that. Also how can I call the WinMain within FormLoad as when I tried it required the arguments to be included and the main problem is that I can't add the arguments in a FormLoad.
any suggestion to how can I resolve this problem?
Sorry but don't know the easy way to explain this. But keep in mind the problem that the hService returns 0.
Ok just to simplify this question:
How to call this type of Function that's starts with HRESULT at the beginning please check above. What I want is to fire that Function, I think that will simplify this even though there's another question about calling it on FormLoad but first I want to know how to call/fire that kind of Function?
The problem is that the IDE says I can not have the int WinMain on Windows Form because its already has something like that but when I'm working with command its works. I can have WinMain and Main but can't have WinMain and FormLoad not inside but within the project or page. To understand please create a Windows Form App and try typing the int WinMain code you will see what's my problem here.
I have found the great tutorial that gives a good reason why I'm getting this problem:
https://msdn.microsoft.com/en-us/library/bb384843.aspx

Why is it CString::LoadString works in the main module(.exe) of my app but will not work in my extensionDLL?

I have this MFC app that loads strings from string resource using CString::LoadString function. Each of the apps dialogue box's classes and its associated resources are contained in an MFC extension DLL.
CString::LoadString loads strings from the main module's(.exe) resource's string resource successfully but fails to load string from the DLL's resource's string resource.
In each case I get my instance handle for load string from CWinApp object by calling :
CWinApp *WinApp = AfxGetApp(),
and of course the instance's handle is WinApp->m_hInstance which I use as the first argument in my call to CString::LoadString function.
What could be the cause and what could be the solution.
Are you passing the EXE's HINSTANCE to load a string from the extension library? Sounds like it.
With MFC, if you have extension libraries and you make sure your string identifiers are unique, you just need to call the CString::LoadString(UINT nID) version. Because extension libraries create CDynLinkLibrary structures that go into a global linked list, the LoadString(UINT) function will search through all your MFC libraries until it finds the HINSTANCE that contains that string, and then it will load from there. If you insist on using the LoadString() function with an HINSTANCE argument, be sure to use the HINSTANCE of the extension DLL, and not the extension of the EXE when you want to load a string or dialog from the DLL.
For small projects, like less than a dozen DLLs, you probably manage to just use unique IDs for everything. When you get into the insanely large projects like 100+ DLLs, then you have to use other techniques like specially named functions in your DLL that call AfxSetResourceHandle() or know to always use the HINSTANCE of the DLL. That's another topic.
Just to complement Joe Willcoxson's answer, be sure to check that every MFC Extension DLL you are using,needs a special initialization code, similar to the example below:
#include "stdafx.h"
#include <afxdllx.h>
static AFX_EXTENSION_MODULE MyExtDLL = { NULL, NULL };
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
TRACE0("MyExt.DLL Initializing!\n");
// Extension DLL one-time initialization
if (!AfxInitExtensionModule(MyExtDLL, hInstance))
return 0;
new CDynLinkLibrary(MyExtDLL);
}
else if (dwReason == DLL_PROCESS_DETACH)
{
TRACE0("MyExt.DLL Terminating!\n");
// Terminate the library before destructors are called
AfxTermExtensionModule(MyExtDLL);
}
return 1; // ok
}
This code just takes care of CDynLinkLibrary creation, the key to share resources between MFC modules.
If all this are setup correctly -- and without ID clashes -- then it's simply a mather of calling:
CString str;
str.LoadString(IDS_MY_STRING_ID);
anywhere in your code, no matter where the string actually persists.
A good start point on resource IDs and numbering can be found in this link.

GetModuleHandle(NULL) vs hInstance

When programming using the Windows API, I've always made the HINSTANCE from WinMain a global variable immediately. If I want to make an OK button, I'd do it like so (given global HINSTANCE g_hInstance):
return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, g_hInstance, NULL);
but lately I've been seeing the instance handle determined without having to be passed as a parameter or clogging up the global namespace, using a call to GetModuleHandle(NULL)*. So, the example above would look like this:
return CreateWindow("BUTTON", "OK", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON, 10, 10, 100, 30, exampleParentWindow, EXAMPLECHILDID, GetModuleHandle(NULL), NULL);
*If your compiler supports it, you can write GetModuleHandle(nullptr) and the statement will have the same result.
What's the advantage (if any) of calling GetModuleHandle(NULL) over explicitly specifying the instance handle?
Fine Print: I know this has an answer, but it has not been phrased as its own question on StackOverflow.
In an EXE, it does not make any difference. hInstance from WinMain() and GetModuleHandle(NULL) both refer to the same HINSTANCE (the module of the .exe file). But it does make a difference if you are creating windows inside of a DLL instead, since you have to use the DLL's hInstance but GetModuleHandle(NULL) will still return the HINSTANCE of the EXE that loaded the DLL.
HMODULE WINAPI GetModuleHandle( _In_opt_ LPCTSTR lpModuleName );
Give the module handle of the module name passed.If you are passing NULL, the you get the module handle of the EXE which is currently running.
If you specifically name the module name, you get the module handle of that dll which is mapped to the process address space.
The use is that when you are trying to call a function exported by the dll, or trying to use a dialog template in side that dll.At that time if you use the HMODULE returned form GetMoudleHandle(NULL) your code wont work.
Just to add my two-cents to these answers. In case you need to get the module handle from within a DLL (and don't want to, or can't save it in a global variable from the DllMain call) you can use this function to get it instead:
HMODULE getThisModuleHandle()
{
//Returns module handle where this function is running in: EXE or DLL
HMODULE hModule = NULL;
::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)getThisModuleHandle, &hModule);
return hModule;
}
One potential gain you get from using GetModuleHandle(NULL) over directly using the WinMain HINSTANCE comes more from architecture. If you want to provide a platform-independent system that runs on linux/windows/whatever you can have a layer that does platform-dependent translations. If that's the case you don't want platform dependent objects such as HINSTANCE showing up in the main application code. So, to circumvent that platform-dependence I put GetModuleHandle(NULL) in the constructor of the platform-dependent class which has the same effect that direct use of the WinMain HINSTANCE does but that abstracts that specific functionality out of the main codebase itself.

C++ - Basic WinAPI question

I am now working on a some sort of a game engine and I had an idea to put everything engine-related into a static library and then link it to my actual problem.
Right now I achieved it and actually link that library and every functions seem to work fine, except those, which are windows-related.
I have a chunk of code in my library that looks like this:
hWnd = CreateWindow(className, "Name", WS_OVERLAPPED | WS_CAPTION | WS_EX_TOPMOST,
0, 0,
800, 600,
NULL, NULL, GetModuleHandle(NULL), this);
if (hWnd) {
ShowWindow(hWnd, SW_NORMAL);
UpdateWindow(hWnd);
} else {
MessageBox(NULL, "Internal program error", "Error", MB_OK | MB_ICONERROR);
return;
}
When this code was not in the library, but in the actual project, it worked fine, created the window and everything was ok. Right now (when I'm linking to my library that contains this code) CreateWindow(...) call returns NULL and GetLastError() returns "Operation succesfully completed" (wtf?).
Could anybody help me with this? Is it possible to create a window and display it using a static library call and why could my code fail?
Thank you.
Ah, maybe you've run into this problem described in an MSDN blog:
If you're writing a static library, you may have need to access the HINSTANCE of the module that you have been linked into. You could require that the module that links you in pass the HINSTANCE to a special initialization function, but odds are that people will forget to do this.
If you are using a Microsoft linker, you can take advantage of a pseudovariable which the linker provides.
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase)
The pseudovariable __ImageBase represents the DOS header of the module, which happens to be what a Win32 module begins with. In other words, it's the base address of the module. And the module base address is the same as its HINSTANCE.
So there's your HINSTANCE.
So, instead of passing GetModuleHandle(NULL) to CreateWindow, try ((HINSTANCE)&__ImageBase) (make sure it is declared as shown in the blog first).
Edit:
From the comments in that blog entry, one mentions the use of GetModuleHandleEx(), perhaps this is a more Compiler/Linker-agnostic approach.