Exporting a MFC Dialog from a DLL - visual-c++

21st July: Updated, see bottom
In VC++ 2005 I have 2 projects. Firstly, a MFC DLL project (not an extension DLL) which has a simple dialog:
TestDlg.h
#pragma once
#include "afxwin.h"
#include "resource.h"
// CTestDlg dialog
namespace Dialogs
{
class __declspec(dllexport) CTestDlg : public CDialog
{
DECLARE_DYNAMIC(CTestDlg )
public:
CTestDlg (CWnd* pParent = NULL); // standard constructor
virtual ~CTestDlg ();
// Dialog Data
enum { IDD = IDD_TEST_DLG };
}
}
Then I have a Win32 console app, with MFC libraries, that does:
TestApp.cpp
#include "stdafx.h"
#include "TestApp.h"
#include <TestDlg.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
Dialogs::CTestDlg dlg;
dlg.DoModal();
}
return nRetCode;
}
It builds and runs up, but no dialog appears. Stepping into DoModal()...
dlgcore.cpp
INT_PTR CDialog::DoModal()
{
// can be constructed with a resource template or InitModalIndirect
ASSERT(m_lpszTemplateName != NULL || m_hDialogTemplate != NULL ||
m_lpDialogTemplate != NULL);
// load resource as necessary
LPCDLGTEMPLATE lpDialogTemplate = m_lpDialogTemplate;
HGLOBAL hDialogTemplate = m_hDialogTemplate;
HINSTANCE hInst = AfxGetResourceHandle();
if (m_lpszTemplateName != NULL)
{
hInst = AfxFindResourceHandle(m_lpszTemplateName, RT_DIALOG);
HRSRC hResource = ::FindResource(hInst, m_lpszTemplateName, RT_DIALOG);
hDialogTemplate = LoadResource(hInst, hResource);
}
if (hDialogTemplate != NULL)
lpDialogTemplate = (LPCDLGTEMPLATE)LockResource(hDialogTemplate);
// return -1 in case of failure to load the dialog template resource
if (lpDialogTemplate == NULL)
return -1;
... more stuff
For whatever reason it seems it can't load the resource, returning -1 at the end of the copied section. I've looked at a few articles on CodeGuru, etc, and not seen anything obvious. Is my class not being exported/imported right? Or is it a resource problem? Or is the problem that I'm trying to display it from a console (MFC) app?
21st July Update
I created an overridden DoModal as so:
INT_PTR CTestDlg::DoModal()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState( ));
return CDialog::DoModal();
}
This seems to work although should I be overriding a different method to get the functionality more generic?

As you've noted, the problem is that MFC is not finding the resource, since the module context is set to your main EXE rather than the DLL containing the dialog resource.
Manually calling AFX_MANAGE_STATE to ensure the DLL context is established is one way to work this, but it's not transparent. The ideal way is to compile your DLL as an extension DLL, so that MFC can take care of loading the resource from a list of extension DLLs and managing memory between the DLLs.
You may be able to short-cut creating the extension DLL and simply create your own CDynLinkLibrary instance, which adds your DLL to the main resource list. I have not tried this, preferring instead to take the extension dll _AFXDLL route, so this may or may not work.
The MSDN article on Extension DLLs may help you determine if they are suitable in your case, and what advantages/drawbacks they bring.

Explictly load you *.lib
Hinstance = Loadlibray("*.lib");
AfxSetResourceHandle(Hinstance);
// this way you can load the resource in you dll not the current app's resource.
then destination you code:
CTestDlg dlg;
dlg.DoModal();

I'm not sure if this construction can actually work. If possible, export just a function which opens the dialog inside the DLL.
But perhaps the use of the AFX_MANAGE_STATE-macro can help you.

AFX_MANAGE_STATE did not work for me. In my case, the exe was calling a dialog from another dll which was calling another dialog from 3rd dll. AFX_MANAGE_STATE was returning context of 2nd dll instead of 3rd one. To fix this, I am overriding DoModel and doing the context switching there.
INT_PTR YourDialog::DoModal()
{
HINSTANCE _hInstance = AfxGetResourceHandle();
__try
{
HMODULE dllModule = ::GetModuleHandle("<Your_DlgSourceDll>.dll");
AfxSetResourceHandle(dllModule);
return CDialog::DoModal();
}
__finally
{
AfxSetResourceHandle(_hInstance);
}
}

Related

Why console app hangs when using a shared dll that containg static variable that use mutex?

I have a shared dll library that contains a class as below :
inside A.dll >> Header File :
class API ErrorHandler
{
public:
ErrorHandler();
virtual ~ErrorHandler();
protected:
static ErrorHandler* defaultHandler();
private:
static ErrorHandler* _pHandler;
static std::mutex _mutex;
};
source(.cpp)
ErrorHandler* ErrorHandler::_pHandler = ErrorHandler::defaultHandler();
std::mutex ErrorHandler::_mutex;
ErrorHandler::ErrorHandler()
{
}
ErrorHandler::~ErrorHandler()
{
}
ErrorHandler* ErrorHandler::defaultHandler()
{
static SingletonHolder<ErrorHandler> sh;
return sh.get(); **<<====== here we get hanged** see the declaration of get
}
SingletoneHolder header file
template <class S>
class SingletonHolder
{
public:
SingletonHolder():
_pS(0)
{
}
~SingletonHolder()
{
delete _pS;
}
S* get()
{
std::lock_guard<std::mutex> lock(_m); <===== cause thread hang
if (!_pS) _pS = new S;
return _pS;
}
private:
S* _pS;
std::mutex _m;
};
After building the above code (every thing related to compiler setting configured correctly) now I want to use it in my console app.
After running console app, app hangs and never reach to main function.
Why std::lock_guard<std::mutex> lock(_m); hangs and prevent main thread to continue executing?
What is alternative?
I am using VS2013 Update5.
content of main file :
#include "ErrorHandler" <== when remove this include app run correctly
#include <iostream>
int main()
{
getchar();
return 0;
}
First, you should post exact contents of the main - with an empty main everything works. Things go south when the ErrorHandler class is being instantiated inside main.
Second, the initialization of your static members occurs inside __DllMainCRTStartup and as stated in the SO question I marked as duplicate, MSDN states that using synchronization primitives from __DllMainCRTStartup can cause a deadlock. A possible solution is to switch to a critical secion.

I can't figure out how to link msi.lib to my Visual Studio C++ project

I'm trying to write a simple application that will enumerate all the ProductCodes installed on my machine.
I've started a new project in Visual Studio 2013, but whenever I build I get the error:
"LNK2019: unresolved external symbol _MsiEnumProductsExA#32 referenced in function _main"
I've been trying to figure out how to add msi.lib to my project include path, but I can't seem to figure it out.
Here's my code:
#define _WIN32_MSI 300
#include <Windows.h>
#include <iostream>
#include <string>
#include <Msi.h>
using namespace std;
int main() {
// Get a list of all installed MSIs
DWORD index = 0;
TCHAR currentProductCode[40] = {0};
unsigned int result = ERROR_SUCCESS;
// Open an MSI handle
while (ERROR_SUCCESS == result) {
result = MsiEnumProductsEx(NULL, "s-1-1-0",
MSIINSTALLCONTEXT_USERMANAGED | MSIINSTALLCONTEXT_USERUNMANAGED | MSIINSTALLCONTEXT_MACHINE,
index, currentProductCode, NULL, NULL, NULL);
if (result == ERROR_SUCCESS) {
cout << "current ProductCode: " << currentProductCode;
}
index++;
}
return 0;
}
I've been trying to update the project's Property Pages by adding the path to the msi.lib to the "Library Directories" property, but that doesn't seem to work:
This is like Visual Studio 101, what am I missing?!
Goto Configuration Properties>Linker>Input
Add msi.lib in Additional Dependencies Thats it! Make sure you are using same calling conversion, which used to built the lib. i.e either stdcall or cdecl.

Cannot convert from 'LRESULT (__clrcall....) to 'WNDPROC'

I try to create a managed C++ assembly in VS 2010 to interface with WinAPI and use it in my other C# assemblies. I've read all posts, even searched in code in GitHub, with no success.
Maybe its about the __clrcall in the error message, should not it be __stdcall? Any ideas?
The exact error message is:
error C2440: '=' : cannot convert from 'LRESULT (__clrcall xxx::Win32Demo::* )(HWND,UINT,WPARAM,LPARAM)' to 'WNDPROC'
The source code:
#pragma once
using namespace System;
using namespace System::Drawing;
#include "stdafx.h"
#include "windows.h"
namespace xxx
{
ref class Win32Demo
{
private: HWND__ * handle;
private: static Char * windowClass;
public:
Win32Demo(void)
{
}
static Win32Demo()
{
tagWNDCLASSEXW w;
windowClass = (wchar_t*) L"Hello";
w.cbSize = sizeof(tagWNDCLASSEXW);
w.style = 0x803;
w.lpfnWndProc = WindowProc; // Error
w.cbClsExtra = 0;
w.cbWndExtra = 0;
w.hInstance = 0;
w.hIcon = 0;
w.hCursor = 0;
w.hbrBackground = CreateSolidBrush(0);
w.lpszMenuName = NULL;
w.lpszClassName = windowClass;
w.hIconSm = 0;
}
public :
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return 0;
}
};
}
This goes wrong because your WndProc() function is being compiled to IL, not machine code. Which happened because you compile it with /clr in effect. It is not just a compile time error, it also cannot work at runtime. Windows doesn't know how to call a managed method, not without the kind of help you get from Marshal::GetFunctionPointerForDelegate().
It is better to just not go there. Either move this code in a separate .cpp file that you compile without the /clr option. Or use #pragma managed(push, off) before this code so that it gets compiled to machine code instead of IL.
And consider the managed class wrappers that give you the same kind of functionality. Like the classes in the System.Windows.Forms namespace. Or if you want to keep this code then derive your own class from the NativeWindow class to attach the window handle, allowing you to override WndProc() with managed code.
Apparently the __stdcall calling convention is not supported for methods of managed classes. So you'll need to put WindowProc inside an unmanaged class:
class WindowProcCallback
{
public:
static LRESULT __stdcall WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
...
}
};
ref class Win32Demo
{
...
};
One suggestion: turn on warnings so that you get warnings about stuff like this. With warnings you would have gotten the following warning:
warning C4441: calling convention of '__stdcall ' ignored; '__clrcall ' used instead

Sharing a JavaVM* across threads in Android NDK

I want to call Java class methods from a cpp file that receives call backs from another executable.
To achieve this, I have retrieved a JavaVM pointer using the android::AndroidRuntime::getJavaVM() method in the .cpp file that directly receives JNI method calls. I am sharing this JavaVM pointer via the constructor to the eventual .cpp file where I call required Java methods as follows:
/* All the required objects(JNIEnv*,jclass,jmethodID,etc) are appropriately declared. */
**JNIEnv* env;
jvm->AttachCurrentThread(&env, NULL);
clazz = env->FindClass("com/skype/ref/NativeCodeCaller");
readFromAudioRecord = env->GetStaticMethodID(clazz, "readFromAudioRecord", "([B)I");
writeToAudioTrack = env->GetStaticMethodID(clazz, "writeToAudioTrack", "([B)I");**
However, I get a SIGSEGV fault running this code.
According to the JNI documentation this seems to be the appropriate way to obtain JNIEnv in arbitary contexts: http://java.sun.com/docs/books/jni/html/other.html#26206
Any help in this regard will be appreciated.
Regards,
Neeraj
Global references will NOT prevent a segmentation fault in a new thread if you try to use a JNIEnv or JavaVM reference without attaching the thread to the VM. You were doing it properly the first time around, Mārtiņš Možeiko is mistaken in implying that there was something wrong with what you were doing.
Don't remove it, just learn how to use it. That guy doesn't know what he's talking about, if it's in jni.h you can be pretty sure it's not going anywhere. The reason it's not documented is probably because it's ridiculously self explanatory. You don't need to create GlobalReference objects or anything either, just do something like this:
#include <jni.h>
#include <string.h>
#include <stdio.h>
#include <android/log.h>
#include <linux/threads.h>
#include <pthread.h>
#define LOG_TAG "[NDK]"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
static pthread_mutex_t thread_mutex;
static pthread_t thread;
static JNIEnv* jniENV;
void *threadLoop()
{
int exiting;
JavaVM* jvm;
int gotVM = (*jniENV)->GetJavaVM(jniENV,&jvm);
LOGI("Got JVM: %s", (gotVM ? "false" : "true") );
jclass javaClass;
jmethodID javaMethodId;
int attached = (*jvm)->AttachCurrentThread(jvm, &jniENV,NULL);
if(attached>0)
{
LOGE("Failed to attach thread to JavaVM");
exiting = 1;
}
else{
javaClass= (*jniENV)->FindClass(jniENV, "com/justinbuser/nativecore/NativeThread");
javaMethodId= (*jniENV)->GetStaticMethodID(jniENV, javaClass, "javaMethodName", "()V");
}
while(!exiting)
{
pthread_mutex_lock(&thread_mutex);
(*jniENV)->CallStaticVoidMethod(jniENV, javaClass, javaMethodId);
pthread_mutex_unlock(&thread_mutex);
}
LOGE("Thread Loop Exiting");
void* retval;
pthread_exit(retval);
return retval;
}
void start_thread(){
if(thread < 1)
{
if(pthread_mutex_init(&thread_mutex, NULL) != 0)
{
LOGE( "Error initing mutex" );
}
if(pthread_create(&thread, NULL, threadLoop, NULL) == 0)
{
LOGI( "Started thread#: %d", thread);
if(pthread_detach(thread)!=0)
{
LOGE( "Error detaching thread" );
}
}
else
{
LOGE( "Error starting thread" );
}
}
}
JNIEXPORT void JNICALL
Java_com_justinbuser_nativecore_NativeMethods_startThread(JNIEnv * env, jobject this){
jniENV = env;
start_thread();
}
Solved the problem. The segmentation fault was because I could not retrieve a jclass object from the JNIEnv object retrieved from the shared jvm pointer.
I propogated a Global reference jclass object alongwith the jvm and the problem was solved.
Thanks for your help Mārtiņš Možeiko!..
Regards,
Neeraj

Can't display images on a gtkmm-based gnome-panel applet

I ran into troubles trying to create a gnome-panel applet with gtkmm. I dealt with most of them, but I'm now kind of blocked.
Quick summary : I tried libpanelappletmm, but every program (even the examples supplied in the source code) segfaults when I try to add the applet in my panel.
So I now use the C library (libpanel-applet). First I looked for a way to wrap the PanelApplet Gobject in a gtkmm C++-object, for example a Gtk::EventBox (PanelApplet inherits from GtkEventBox). I tried to cast it, but Glibmm kept throwing a warning ("Failed to wrap object 'PanelApplet'").
So I created a class "Info", inheriting from Gtk::HBox. In my main.cpp file I declare an instance of it, get the underlying GTK object (gobj method), and use the GTK+ functions to add it into the PanelApplet.
Here's my main.cpp.
#include <iostream>
#include <gtkmm.h>
#include <panel-applet.h>
#include "Info.hpp"
static void manage_timeboxes(BonoboUIComponent *uic, void *applet, const char* data) {
std::cout << "manage" << std::endl;
}
static gboolean getApplet(PanelApplet *applet, const gchar *iid, gpointer data) {
/*
if(iid != "OAFIID:TimeboxingApplet")
return false;
*/
Glib::init();
Gtk::Widget* content = new Info();
gtk_container_add(GTK_CONTAINER(applet), content->gobj());
static const char menu_xml[] =
"<popup name=\"button3\">\n"
" <menuitem name=\"Manage\" "
" verb=\"manage_timeboxes\" "
" _label=\"_Gérer l'emploi du temps\"\n"
" pixtype=\"stock\" "
" pixname=\"gtk-properties\"/>\n"
"</popup>\n";
static const BonoboUIVerb linked_verbs[] = {
BONOBO_UI_VERB ("manage_timeboxes", manage_timeboxes),
BONOBO_UI_VERB_END
};
panel_applet_setup_menu(applet, menu_xml, linked_verbs, data);
gtk_widget_show_all(GTK_WIDGET(applet));
return true;
}
PANEL_APPLET_BONOBO_FACTORY (
"OAFIID:TimeboxingApplet_Factory",
PANEL_TYPE_APPLET,
"Timeboxing",
"0.0",
getApplet,
NULL)
It works fine if I add labels or buttons in my Info object.
But then I tried to add an icon.
My first try was adding a Gtk::Image as a property of Info.
Info.hpp
#ifndef TIMEBOXING_INFO_H
#define TIMEBOXING_INFO_H
#include <gtkmm/box.h>
#include <gtkmm/image.h>
#include <gtkmm/label.h>
class Info : public Gtk::HBox {
public:
Info();
virtual ~Info(){};
protected:
Gtk::Image icon;
Gtk::Label info;
};
#endif
Info.cpp
#include "Info.hpp"
#include <gtkmm/image.h>
#include <gtkmm/label.h>
Info::Info() : icon("/home/bastien/programmation/timeboxing-applet/icons/clock-24.png"), info("<b>En cours</b>") {
info.set_use_markup();
pack_start(icon);
pack_start(info);
show_all_children();
}
When I try to add the applet, I get this error and the program aborts :
glibmm:ERROR:objectbase.cc:78:void Glib::ObjectBase::initialize(GObject*): assertion failed: (gobject_ == castitem)
I commented "Gtk::Image icon" from Info.hpp, and I modified my constructor like this :
Info::Info() : info("<b>En cours</b>") {
info.set_use_markup();
Gtk::Image icon("/home/bastien/programmation/timeboxing-applet/icons/clock-24.png");
pack_start(icon);
pack_start(info);
show_all_children();
}
I'm not getting the Glibmm error anymore, but the image isn't displayed. I tried with another file, with an icon from the stock, and even with a Gdk::Pixbuf.
Thank you in advance !
Well, strangely enough, it works if I create a pointer to Gtk::Image.
If anyone has an explanation, it would be great !
Edit : apparently, I had to call Gtk::Main::init_gtkmm_internals. My wrapping troubles went away. I can wrap PanelApplet too, but if I use the resulting Gtk::EventBox* it doesn't display anything.

Resources