Recently, the project needs to integrate the previously written Vc programs into VS2005, written in c #, and written in the previous dynamic Connection Library of VC, Which is troublesome to rewrite, let C # Call VC dll. However, I encountered a problem: how should I declare the char * type variables used as output parameters in VC to output data correctly?
In general, the output parameters in VC are in the form of pointers or arrays. If a pointer of a common type, such as an integer, the return value can be obtained by adding a data variable with ref in c. So I tried to write the char * output variable in VC into ref string in c # (because char * can be written as string or char [] in c #), however, it cannot be written in this way.
Later, I checked some information on the Internet and found that when char * type data is used as the output parameter, the Data Type in c # should be written as StringBuilder. This not only solves the problem of passed parameters, but also solves the problem of outgoing parameters.
The following example shows how to use C # To Call functions in VC dll:
1. CharSet should use Ansi, Because Vc is Ansi by default, and c # is Unicode. Otherwise, garbled characters are generated. Other DIIImport parameters are as follows. Except for EntryPoint, the other three parameters are optional.
EntryPoint: Specifies the DLL entry point to be called. The default entry name is the name of the hosting method.
CharSet: controls the method for name Rename and sending String parameters (UNICODE by default)
CallingConvention indicates the function call convention of the entry point (WINAPI by default)
SetLastError indicates whether the called party calls the SetLastError Win32 API function before returning from the attribute method (false by default in C)
2. structure Reference Transfer
First, define the same struct as c ++ In c #. If it is a reference transfer, add [In, Out] before the struct, for example:
[DllImport (@ "test. dll")]
Public static extern int test ([In, Out] SLineData [] lndt, ref UInt32 length );
3. If the output parameter of the char ** type is a pointer, or a two-dimensional array or other more complex situations. Refer to the following webpage:
(