Call Native Dll methods and debugging methods in Managed code)

Source: Internet
Author: User

Managed code usually refers. code in NetFramework, such as VB. net, C # code, Native code refers to the code developed with the original C/C ++. Most open-source code is usually Native code, because such code can be compiled and run on a variety of platforms (Windows/Unix/Linux/MacOs), Managed code, because currently.. Net Framework does not have compatibility with multiple platforms. It can only run on Windows.

The concept of a DLL developed by calling Native code from Managed code is called Platform Invoke, as shown in. See. Net Framework advanced development-A Closer Look at Platform Invoke.

Call Native code

If you have a Native source code, you can not only call it, but also Debug it ). If no source program exists, only executable parts, such as DLL, can be called and cannot be debugged.

To call Native code, you just need to compile the code into a DLL and place it in the same directory of the calling program. Then you can call the function in world. dll.

If you have Native source code, you can create a Solution in vs2k5 (Visual Studio2005) to manage the code and Native code) the Code creates projects respectively ). In vs2k5, code with different syntaxes cannot be compiled in the same Project.

For example, in Solution, add a VB named hello. net Project. The Project type is WindowApplication, that is, the target program is an exe program. Then, add a C ++ Project called world. The Project type is Win32Project, select the DLL mode.

Although it is a C ++ project, it can also compile C language programs. If it is a C language program, select the "Compile as C Code" mode in the Property of the C ++ project. The specific location is as follows.

Configuration Properties -> C/C++ -> Advanced -> Compile As

By default, the target directory of the C ++ project is different from that of the Managed code. In this way, when the Managed code calls the DLL, the DLL cannot be found. You can use the following two methods to solve this problem.

One way is to modify the target directory settings of the C ++ project, which is the same as the target directory of the Managed code. This method has a small defect. If there are multiple executable programs in the Solution, this setting can only solve the problem that one program calls the DLL. The settings are as follows.

Project Property)-> ConFiguratiOn PropeRties->General-> OutpUt DiretOry

Another method is to add a copy command in Post-BuildEvent of the c ++ project to copy the target DLL to the corresponding target directory. This method can copy the target DLL to any target directory. Vs2k5 is intelligent. During program debugging, when you find that the DLL to be loaded is the same as the target DLL of a project, it will load the target DLL and debugging information of the project,. The settings are as follows.

Project Property)-> ConFiguratiOn PropeRties->Build EVents->Post-BuIld EvenT-> ComMand LinE

An example of a command line is as follows.

Copy $ (TArgetPatH) target directory 1
Copy $ (TArgetPatH) target directory 2
Copy $ (TArgetPatH) target directory 3

The call relationship between Managed code projects and Native DLL projects forms a project dependency ). That is to say, Native DLL projects should be compiled before the project is called. This dependency is imperceptible to vs2k5 and needs to be set manually. Each Native DLL call project must be set as a dependent DLL project, in this way, the correct compilation Order can be formed (Build Order ). The settings are as follows.

Menu> ProjEct-> PRoject DEpendencIes-> DEpendencIes
Call Native DLL in VB. Net

In VB. NetDeclareStatement andDllImportYou can call functions in Native DLL in two ways.

The Declare statement is a commonly used method, which is available in earlier versions of VB. An example of a typical Declare statement is as follows.

Declare Auto Function MBox Lib "user32.dll" Alias "MessageBox" ( _
ByVal hWnd As Integer, _
ByVal txt As String, _
ByVal caption As String, _
ByVal Typ As Integer _
) As Integer

In the preceding example, the Lib keyword specifies the DLL name and location (the current directory of the executable program), and the Alias keyword specifies the name of the execution function, the Auto keyword specifies the conversion rules for parameters of the String type. The Declare statement implies that this function is of the Shared type. For more information, see the VB Reference Manual: Declare Statement.

DllImport is a method introduced in VB. Net. An example of a typical DllImport statement is as follows.

Imports System.Runtime.InteropServices
...
<DllImport ("user32.dll", EntryPoint:="MessageBox")> _
Public Shared Function MessageBox (
ByVal hWnd As Integer, _
ByVal txt As String, ByVal caption As String, _
ByVal Typ As Integer _
) As IntPtr
End Function

In the preceding example, the first parameter is dllName, which specifies the DLL name and location (the current directory of the executable program), The EntryPoint parameter is the second parameter, and the name of the execution function is specified. If you want to specify the conversion rules for String-type parameters as in the Declare statement, you can use the CharSet parameter. Note that such functions or subprograms must be of the Shared type and should be empty functions or Sub programs.

DllImport has many parameters, So compared with the Declare statement, you can specify the details of calling Native DLL in more detail. The parameters of DllImport are dllName, BestFitMapping, CallingConvention, CharSet, EntryPoint, ExactSpelling, PreserveSig, SetLastError, and ThrowOnUnmappableChar. For more information, see the. Net Class Library Reference Manual DllImportAttribute Members.

Formally speaking, the features of the DllImport attribute and Declare statement are roughly the same, but the use of the DllImport attribute has an advantage that vs2k5 can check the parameter type and Native (Native) during compilation) if the function parameters in the DLL are matched, The Declare statement does not have this check. The check only happens when the corresponding function is executed.

Parameter mail (Marshal)

The main trouble for calling Native DLL is parameter encapsulation, that is, how parameters in VB. Net or Managed code interact with functions in Native DLL. The following table lists some common Types of mappings. This table comes from Visual Studio programming Description: Platform Invoke Data Types.

Unmanaged type (Wtypes. h) Unmanaged type (c) Managed type Description
HANDLE Void * System. IntPtr 32-bit or 64-bit
BYTE Unsigned char System. Byte 8-digit
SHORT Short System. Int16 16-bit
WORD Unsigned short System. UInt16 16-bit
INT Int System. Int32 32-bit
UINT Unsigned int System. UInt32 32-bit
LONG Long System. Int32 32-bit
BOOL Long System. Int32 32-bit
DWORD Unsigned long System. UInt32 32-bit
ULONG Unsigned long System. UInt32 32-bit
CHAR Char System. Char ANSI
LPSTR Char * System. String or System. Text. StringBuilder ANSI
LPCSTR Const char * System. String or System. Text. StringBuilder ANSI
LPWSTR Wchar_t * System. String or System. Text. StringBuilder Unicode
LPCWSTR Const wchar_t * System. String or System. Text. StringBuilder Unicode
FLOAT Float System. Single 32-bit
DOUBLE Double System. Double 64-bit

Parameter type sending is quite complex, and different types have different corresponding methods. For String, Class, Structure, Union, Array, function Callback, void pointer (void *) there are various corresponding methods. In Visual Studio programming Description: there are multiple sections in Marshaling Data with Platform Invoke, as well as multiple examples.

Of course, there is also a simple method to solve the parameter mail (parameter Al), that is, to go to the Internet to find the envelope al code written by someone else, for example, you can use the corresponding function name to search for it in Google Group.

Create a special class for DLL Functions

Calling Native DLL is not very common. If a program can call the Managed class library to solve the problem, do not call Native DLL. It is recommended that DLL functions be called in a special class for encapsulation. See. Net Framework advanced development-Creating a Class to Hold DLL Functions.

Debug Native DLL

To debug Native DLL, you need the following conditions and steps.

  • The source code of Native DLL must be available.
  • Create a separate Project for the source code of Native DLL ).
  • Add this project to the Solution containing the Managed code project that calls this DLL (Solution ).
  • By setting the target directory of the DLL project or setting the Copy command in the Post-Build Event of the DLL project, the Managed code project can load the corresponding DLL. This article has been described in detail in the previous article.

In addition, you need to pay attention to some settings.

First, the Native DLL project compilation option should be set to generate debugging information in the connector (Linker) section. Otherwise, debugging cannot be performed, breakpoint cannot be set, and code tracing cannot be performed, debugging at the Assembly level is supported at most. In general, the project has two Configuration items: Debug and Release. In the Debug Configuration, you need to set the debugging information to generate the Release. Set the location to Yes as follows.

Project Property)-> ConFiguratiOn PropeRties->Linker-> DebugGing->GenerateDebug INfo

Next, you need to enable the Mixed debugging Mode for Managed code projects ). For example, for a VB. Net project, set the position as follows and check before setting. See Visual Studio Application Development-How to: Debug in Mixed Mode.

Project Property)-> DebUg-> (ENable DeBuggers)EnableUnmanageD code dEbugging


References

  • Visual Basic programming guide-Walkthrough: Calling Windows APIs
  • . Net Framework advanced development-Consuming Unmanaged DLL Functions
  • Visual Studio Application Development-Debugging DLL Projects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.