如何在VB.NET中使用<DllImport>?

Mil*_*ike 25 vb.net dllimport

我应该如何DLLImport在VB.NET中的东西?一个例子是:

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetWindowText(ByVal hwnd As IntPtr, ByVal lpString As StringBuilder, ByVal cch As Integer) As Integer

End Function
Run Code Online (Sandbox Code Playgroud)

如果我把它放在一个类或其他地方,我得到"DLLimport未定义"我使用的是Visual Studio 2008 Professional

Ant*_*lev 36

您必须添加Imports System.Runtime.InteropServices到源文件的顶部.

或者,您可以完全限定属性名称:

<System.Runtime.InteropService.DllImport("user32.dll", _
    SetLastError:=True, CharSet:=CharSet.Auto)> _
Run Code Online (Sandbox Code Playgroud)


Luh*_*ann 7

Imports System.Runtime.InteropServices
Run Code Online (Sandbox Code Playgroud)


小智 7

我知道这个问题已经得到了回答,但这里有一个针对尝试在 vb 项目中使用 SQL Server 类型的人的示例:

            Imports System
            Imports System.IO
            Imports System.Runtime.InteropServices

            Namespace SqlServerTypes
                Public Class Utilities



                    <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
                    Public Shared Function LoadLibrary(ByVal libname As String) As IntPtr

                    End Function

                    Public Shared Sub LoadNativeAssemblies(ByVal rootApplicationPath As String)
                        Dim nativeBinaryPath = If(IntPtr.Size > 4, Path.Combine(rootApplicationPath, "SqlServerTypes\x64\"), Path.Combine(rootApplicationPath, "SqlServerTypes\x86\"))
                        LoadNativeAssembly(nativeBinaryPath, "msvcr120.dll")
                        LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial140.dll")
                    End Sub

                    Private Shared Sub LoadNativeAssembly(ByVal nativeBinaryPath As String, ByVal assemblyName As String)
                        Dim path = System.IO.Path.Combine(nativeBinaryPath, assemblyName)
                        Dim ptr = LoadLibrary(path)

                        If ptr = IntPtr.Zero Then
                            Throw New Exception(String.Format("Error loading {0} (ErrorCode: {1})", assemblyName, Marshal.GetLastWin32Error()))
                        End If
                    End Sub
                End Class
            End Namespace
Run Code Online (Sandbox Code Playgroud)


Nap*_*Nap 5

我在pinvoke.net上的getwindowtext(user32)中看到,您可以放置​​一个MarshalAs语句来声明StringBuffer等效于LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function
Run Code Online (Sandbox Code Playgroud)