Managed C++ Tidbit of the day:
Today, I wrote an app that calls Win32 functions from a member function of a __gc class. Here's the code for the component that actually calls the function:
// component1.h
#pragma once #include <windows.h>
[System::Runtime::InteropServices::DllImport("user32", CharSet=System::Runtime::InteropServices::CharSet::Auto)] WINUSERAPI int WINAPI GetSystemMetrics(IN int);
namespace component1 { public __gc class Class1 { public: static void testmethod() { // system metrics int nReturn; if ((nReturn = GetSystemMetrics(SM_CMONITORS)) != 0) { System::Console::Write(S"{0} Display Monitor",__box(nReturn)); if (nReturn != 1) System::Console::Write(S"s"); System::Console::WriteLine(); } } }; }
The above code was added to the main header file of a "Managed C++ Class Library" wizard-generated project. I called this component from a "Managed C++ Application" wizard-generated project. Here's the code for that:
// This is the main project file for VC++ application project // generated using an Application Wizard.
#include "stdafx.h" #using <mscorlib.dll> #using "component1.dll" #include <tchar.h> using namespace System; using namespace component1;
// This is the entry point for this application
int _tmain(void) { Class1::testmethod(); return 0; }
A couple of things - my Win32 call didn't happen when I had "using" statements for System and System::Runtime::InteropServices in my class library. That is why I fully qualify the .NET library names in my class library code.
Also, because of the rules of assembly binding, I had to change my class library's output file (in the linker settings) to put the generated .dll into the output directory of my .exe project (this seemed like the most convenient place). In addition, the .exe project needs to refer to the generated .dll file during compilation, so I had to set the .exe project's /AI compiler switch to specify "./debug" (look for the .dll in the output directory). One more thing: I had to specify that my .exe project depends on my .dll project in the project dependencies dialog.
A little bit of progress...
10:13:03 PM
|