Updated: 1/22/2004; 8:04:38 PM.
ronpih I guess...
Your guess is as good as mine...
        

Wednesday, March 13, 2002

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    comment []

© Copyright 2004 Ronald Pihlgren.
 
March 2002
Sun Mon Tue Wed Thu Fri Sat
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
Feb   Apr

Weblogs
Microsoft Testers
VC++ Bloggers
Links
Note:This is a personal weblog. All opinions expressed here are mine alone.


Click here to visit the Radio UserLand website.

Subscribe to "ronpih I guess..." in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.