1

I asked a question some time ago here: COM vs non-COM DLL about calling a classic C++ program from .NET.

The answer (from Hans Passant) was to write a wrapper class in Visual C++, which worked out well in my project (I did get some help with this from another developer who is more commerically experienced with C++).

My question is: is there wrapper classes created for some of the functions in the WINAPI. For example, the code below works without a wrapper class:

Imports System.Runtime.InteropServices
Imports System.Text

Public Class Form1

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
    Public Shared Function MessageBox(ByVal hwnd As IntPtr, <MarshalAs(UnmanagedType.LPStr)> ByVal lpString As String, <MarshalAs(UnmanagedType.LPStr)> ByVal lpString2 As String, ByVal cch As Integer) As Integer
    End Function

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        MessageBox(0, "HelloWorld", "HelloWorld", 0)
    End Sub
End Class
Community
  • 1
  • 1
w0051977
  • 15,099
  • 32
  • 152
  • 329

2 Answers2

4

The existing wrapper classes around WINAPI calls are called the System.Windows namespace. ;-)

Pieter Geerkens
  • 11,775
  • 2
  • 32
  • 52
2

Hans' comment on your other question said:

You cannot directly use a C++ DLL that exports classes in a .NET program. A wrapper written in the C++/CLI language is required.

As he said, the reason, in that situation, why a wrapper was needed is because .NET cannot use a class that is exported by C++. In this case, however, the MessageBox function is simply a function that is exported by a DLL that was compiled from C++, not a class. VB.NET can very easily be used to invoke API functions, as you have demonstrated. The problem is not with calling API functions. The problem is with using C++ classes.

As others have said, though, in this case, you just want to use the managed MessageBox.Show.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
  • Thanks +1 for clarifying that. Is this why you can only reference Shared members using DLLIMPORT? I would always use MessageBox.Show. The reason I ask the question is to learn. – w0051977 Feb 28 '13 at 19:23
  • I'm not at all familiar with windows programming in C++, but from what I do know, yes. You certainly couldn't import an instance method of a class since doing so would require an instantiation of an object of that type first. – Steven Doggart Feb 28 '13 at 19:27
  • C++ is an object oriented programming language. Why can't yo create an instance of a class without creating a wrapper? – w0051977 Feb 28 '13 at 23:00
  • 1
    .NET is only capable of importing classes from other .NET DLL's and from COM DLL's (indirectly via an interop DLL). The issue is not the object orientation. The issue is the technology via which the classes are exposed. – Steven Doggart Mar 01 '13 at 00:46