Loading DLL fails on Windows - c++

As a Xcode developer I have to use my written code on windows, too. I think I have successful master all cross platform issues but now I have a real problem understanding the DLL hell on Windows.
I used my code with Xcode and Gcc (Ubuntu) successful. On Windows I get a error message:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
I read much about this uses but I have my problems to understand the issue.
Normally on windows I have something like
#define MYLIB_API __declspec(dllimport)
I cannot find this inside the header of the Bass Library (bass.h). There is only one line
#define BASSDEF(f) WINAPI f
Now, I try to dynamic load the DLL functions in my code. You can see the dynamic loading header as link on bottom. To much to copy here. This dynamic loading is working for .dylib and .so libs well, not for .dll
My target is to load the DLL dynamic and not static with an additional lib.
In my code I use the bass.h and the bassdecode.h. In my code I call as sample:
bool returnVar = _BASS_SetConfig(BASS_CONFIG_DEV_DEFAULT,1);
And here I get the calling convention message.
What I have to do in my header file to successful import DLL functions on Windows?
You can download the files at: header files to download

Ok, for all who run into the same problem, the solution is the Answer from Hans Passant. I cannot mark this answer as solution so I want to give him the reputation.
My original typedef of the function:
typedef BOOL (*BASS_SetConfig_Type)(DWORD option, DWORD value);
Was searched in DLL
_BASS_SetConfig = (BASS_SetConfig_Type)DllFindSym(m_hMod, "BASS_SetConfig")
Where DLLFindSym is defined as:
#define DllFindSym(handle,name) (GetProcAddress(handle,name))
Now changed the typedef to
typedef BOOL (__stdcall *BASS_SetConfig_Type)(DWORD option, DWORD value);
Now everything works like a charm in Windows. Many thanks to the quick hint from Hans Passant.

Related

MSVC: Unresolved external symbol "__imp_JNI_GetCreatedJavaVMs"

Edit2: Forgot to mention that I am trying to build a 64-bit application.
I need some help here.
For some reason I can't seem to find a way to make this external work and well, before you ask.
I've tried calling LoadLibrary:
// (temp)
// Load JVM library since it's being a dork
HINSTANCE hVM = LoadLibraryA("C:\\Program Files\\Java\\jdk1.8.0_172\\jre\\bin\\server\\jvm.dll");
if (hVM == NULL) { ... }
I have every lib folder included in VC++ Directory, I have also tried putting jvm.lib in same dir and just linking it through pragma comment: #pragma comment(lib, "jvm.lib")
But nothing seems to do the job. :/
Am I maybe looking at the wrong file to begin with? I've tried others like jawt.lib as well.
Edit: I get the function from #include <jvmti.h> but there is no corresponding .lib or .dll file. And every similar function comes from jvm so if it's not that one, which one is it? I'm lost.
My bad, I thought it worked for both 32-bit and 64-bit applications but seems like it only works on 32-bit applications. (Was using a 32-bit JDK install and in my haste I did not realize that.)

DLL calling conventions & access violation

after reading and learning for years on this great platform its my first post now.
My Problem:
In C++ I am trying to create a dynamic linked library (32 bit) that will serve as a AQMP Communication Client (based on SimpleAmqpClient). The dll file will then be used inside a third party application (32 bit).
During my tests where I invoke the dll in a custom executable everything works fine. But when I try to use the dll in the third party application I get an access violation error (0x00000000). I found out that the problem may be the function calling convention.
With the few code lines presented below that error can be reproduced. It disappears if I remove the __stdcall expression in mytest.dll. Normally I would expect the code to work because it uses the same calling convention in custom_test.exe and mytest.dll.
(Sidenote: the third party application expects a __stdcall function thats why I rely on it)
I would like to understand this behavior. Thanks in advance!
My Setup:
OS: Windows 7
32 bit Compiler: gcc 5.3 (Cygwin)
My Code (custom_test.exe):
#include <stdio.h>
#include <windows.h>
int main(void) {
HINSTANCE hInstance;
hInstance=LoadLibrary("mytest.dll");
FARPROC lpfnGetProcessID = GetProcAddress(HMODULE(hInstance), "test");
// Function prototype
typedef void (__stdcall *myFunction)(void);
myFunction test;
test = myFunction(lpfnGetProcessID);
// Call Function
test();
FreeLibrary(hInstance);
}
My Code (mytest.dll):
extern "C" __declspec(dllexport) void __stdcall test(void) {
printf("Inside Function \n");
}
I compile the code via
dll: g++ mytest.cpp -o mytest.dll -shared -std=gnu++11
exe: g++ custom_test.cpp -o custom_test.exe -std=gnu++11
The __stdcall convention makes it the responsibility of the called function to clean up the stack on return, while __cdecl makes it the caller's responsibility.
We can't see the actual declaration in the third-party DLL, but my initial assumption would be that the DLL expects arguments and is either using what it believes to be stack arguments in error, or is cleaning up the stack based on it's assumption of the stack arguments and generally messing with your stack.
EDIT
In this instance though, I see that when compiling in 32 bit, the test function is exported with a name of 'test#0'. If you change your GetProcAddress to use this decorated name instead it will work.
Ok now several hours later I can see clear again! Thx IanM_Matrix1 for the suggestion, the so called name decoration was indeed the point.
After my research I can now share some helpful ressources I found:
It is important to know that some compilers add different decorations to the function names, see here:
http://wyw.dcweb.cn/stdcall.htm
With that in mind one can read this page about Win32 calling conventions in general:
http://www.unixwiz.net/techtips/win32-callconv.html
When using gcc the decorations can also be disabled via the flag -Wl,--kill-at.

Using a function defined in a DLL from C++ code

I built Qt from source (dlls) and am trying to build an application that uses the Qt dlls. I don't have a lot of experience with C++ so I'm running into what I'm sure is a very basic issue.
My builds are failing on the includes with errors like so:
Fatal error: QNetworkProxy: No such file or directory
Here is the g++ command I am using (I also used -L to add the correct folder to the lib path, but that also didn't work):
g++ -l..\..\wkqt\bin\QtCore4.dll -l..\..\wkqt\bin\QtNetwork4.dll -l..\..\wkqt\bin\QtWebKit4.dll -I..\include -Ishared -Ipdf -Ilib -Iimage -o ..\bin\wkhtmltopdf.exe pdf\*.cc lib\*.cc image\*.cc shared\*.cc
I tried in Visual Studio as well (assuming it wouldn't build, but I wanted to see if I could at least include the Qt dlls from there properly) and I am getting the same errors. Am I doing something wrong with the way I am compiling with g++? If I am linking with the Dlls properly then what is the proper way to use Qt functions from my code?
To clarify, I am not looking for how to properly use Qt. My question is: what is the proper way to use functions defined in any Dll from native C++ code? I apologize if this is a very basic question, but I'm unable to find a clear answer on Google and I don't have any experience with C++ and including third party libraries for use from C++ code.
DLLs can be used by dynamicly loading them and calling their used functions.
to call the exposed functions first define their syntax in the begining
suppose function is syntax is
BOOL MyFunction(int a,char* pszString)
then define syntax
#typedef BOOL (WINAPI *PMYFUNCTION)(int a,char* pszString)
then make object
PMYFUNCTION pfnMyFunction;
and get valid pointer by calling GetProcaddress after loadlibrarycall
HMODULE hlib= Loadlibrary("c:\\Mylib.dll");
if(hlib)
{ pfnMyFunction = (PMYFUNCTION)Getprocaddress(hlib,"MyFunction"); }
Hope this helps...

How to declare and link to RoInitialize,RoUninitialize,RoGetActivationFactory and HSTRING Functions in Mingw Gcc

UPDATED: Added what RoInitialize looks like in roapi.h
I am in the process of writing a pure C++11 WinRT library. I do not use WRL or C++/CX (Obviously if I want pure C++11).
I got my code to compile and run on MSVC, but I want to see if I can get the code to compile and run on Mingw Gcc. Specifically, I am using GCC 4.7.2 obtained from nuwen.net.
What I need at this point is a way to call the Windows API Functions RoInitialize, RoUnitialize, RoGetActivationFactory and the HSTRING Functions WindowsCreateString, WindowsDuplicateString, WindowsDeleteString.
I tried compiling this program in G++ but got the error
extern "C"{
__declspec(dllimport)int __stdcall RoInitialize(int);
}
int main(){
RoInitialize(1);
}
I tried to compile but got:
c:\Users\jrb\Desktop>g++ gccwinrt.cpp
C:\Users\jrb\AppData\Local\Temp\ccy7y1V9.o:gccwinrt.cpp:(.text+0x1e): undefined
reference to `_imp__RoInitialize#4'
collect2.exe: error: ld returned 1 exit status
If anybody can point me in the right direction on how to declare these functions and what libraries I need to link to, I would appreciate it. Even if it requires LoadLibrary/GetProcAddress I would still be ok with that
Update: Here is what RoInitialize looks like in the header roapi.h
ROAPI
_Check_return_
HRESULT
WINAPI
RoInitialize(
_In_ RO_INIT_TYPE initType
);
ROAPI is just a define for __declspec(dllimport)
_Check_return_ is part of SAL (Secure Annotations Language?)
HRESULT maps to int32
WINAPI is a define for __stdcall
RO_INIT_TYPE is an enumeration so int should cover it
The import library for these functions is runtimeobject.lib (which the MSDN documentation fails to mention). It can be found in the Windows SDK for Windows 8.
The library you need to link against is windowsapp.lib (and only this lib, remove all others).
This topic lists the Win32 APIs that are part of the Universal Windows Platform (UWP) and that are implemented by all Windows 10 devices. For convenience, an umbrella library named WindowsApp.lib is provided in the Microsoft Windows Software Development Kit (SDK), which provides the exports for this set of Win32 APIs. Link your app with WindowsApp.lib (and no other libraries) to access these APIs.
APIs present on all Windows 10 devices - Microsoft Docs
See that page for a complete list of functions that implements; it includes RoInitialize, RoUnitialize, RoGetActivationFactory and WindowsCreateString, WindowsDuplicateString, & WindowsDeleteString (among many, many others). If you need other functions, you may need to link extension APIs also.
Similar guidance was originally on
https://msdn.microsoft.com/en-gb/windows/uwp/get-started/universal-application-platform-guide#writing-code but is no longer present:
Windowsapp.lib is an "umbrella" lib that provides the exports for the UWP APIs. Linking to Windowsapp.lib will add to your app dependencies on dlls that are present on all Windows 10 device families.
For delay loading, you will need to load api-ms-win-core-winrt-l1-1-0.dll, which is an API set, a collection of APIs that Windows can load regardless of where the actual DLLs are. This specific set is listed as a Windows 8.1 API set, however if you check the documentation for RoInitialize it says the minimum supported client is Windows 8. Assuming you use LoadLibrary and GetProcAddress, it shouldn't matter.
The actual DLL that the method is implemented in is combase.dll, but they use these API set DLLs as a level of indirection so that they are free to change or update that original DLL in the future.
For future reference, the API sets for Windows 10 (UWP) are listed on a separate page to the API sets for Windows 8 (and 8.1). The stub DLL (for delay loading) is the same. https://msdn.microsoft.com/library/windows/desktop/mt186421
Many other APIs also list their corresponding API set in their own documentation. For example, MSDN gives AllowSetForeground as an example.
If you don't have the import lib that contains RoInitialize, you'll need to use LoadLibrary/GetProcAddress to resolve the types.
Run-time link it like this:
#include <roapi.h>
namespace
{
FARPROC LoadComBaseFunction(const char* function_name)
{
static HMODULE const handle = ::LoadLibraryA("combase.dll");
return handle ? ::GetProcAddress(handle, function_name) : nullptr;
}
decltype(&::RoInitialize) GetRoInitializeFunction()
{
static decltype(&::RoInitialize) const function = reinterpret_cast<decltype(&::RoInitialize)>(LoadComBaseFunction("RoInitialize"));
return function;
}
}
HRESULT RoInitialize(RO_INIT_TYPE init_type)
{
auto ro_initialize_func = GetRoInitializeFunction();
if (!ro_initialize_func)
return E_FAIL;
return ro_initialize_func(init_type);
}
Source

How to initialize msvcrt.dll?

If I do a LoadLibrary("msvcrt.dll") do I need to initialize the CRT somehow? Section 2 in the following document seems to say that I do, but I just get an undefined symbol error for _CRT_INIT when I try to call _CRT_INIT:
http://support.microsoft.com/kb/94248
Edit: I should have said that this is for a program that dynamically loads all the dlls that it uses, hence the call to LoadLibrary("msvcrt.dll").
Call DllMain() in it. If it relies on the C runtime, it will call CRT_INIT.
But a far better question is if a program is using something in msvcrt, there's no need to explicitly load the dll and initialize it, so why are you doing this?
If you're working in C++, have you declared _CRT_INIT as extern "C"?
Have you tried using the DUMPBIN utility ( http://support.microsoft.com/kb/177429 -- if you haven't your PATH up yourself, you'll have to use the Visual Studio Command Prompt I think) with the /EXPORTS switch to see which functions are available from the CRT DLL, just to double check?
If you get stuck, VS2005 and earlier (and presumably later...) come supplied with the source code for the runtime library. For VS2005, this is in VC/crt/src, relative to the VS install folder. It looks like _CRT_INIT is the right name -- see crtdll.c and dllcrt0.c, and it's a C function.
You must not call _CRT_INIT() but call CRT_INIT() (if you really must)
The link you referenced refers to using CRT_INIT() only when "Using the CRT Libraries When Building a DLL", and even then it is only one of two alternatives; the first probably being preferable in most cases.