1

前段时间我在这里问了一个问题:COM vs non-COM DLL关于从 .NET 调用经典 C++ 程序。

答案(来自 Hans Passant)是用 Visual C++ 编写一个包装类,这在我的项目中效果很好(我确实从另一个在 C++ 方面更有商业经验的开发人员那里得到了一些帮助)。

我的问题是:是否为 WINAPI 中的某些函数创建了包装类。例如,下面的代码在没有包装类的情况下工作:

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
4

2 回答 2

4

围绕 WINAPI 调用的现有包装类称为System.Windows命名空间。;-)

于 2013-02-28T19:03:02.847 回答
2

汉斯对您的另一个问题的评论说:

您不能直接使用在 .NET 程序中导出类的 C++ DLL。需要使用 C++/CLI 语言编写的包装器。

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.

于 2013-02-28T19:16:18.547 回答