C # keyword extern usage

Source: Internet
Author: User

Modifiers are used to declare methods that are implemented externally. A common use of the extern modifier is to use the Interop service to dial in a non-

Managed code is used with the DllImport property, in which case the method must also be declared as static, as shown in the following example: [DllImport ("Avifil32.dll")]
private static extern void Avifileinit ();

Attention
The extern keyword can also define external assembly aliases so that different versions of the same component can be referenced from a single assembly.

It is an error to use the abstract (C # Reference) with the extern modifier to modify the same member. Using the extern modifier means that the method is implemented outside of the C # code, and the

Using the abstract modifier means that the method implementation is not provided in the class. Attention
The extern keyword has more restrictions on use than in C + +. To compare with the C + + keyword, see Using extern to in C + + Language Reference

Specify Linkage.

In this example, the program receives a string from the user and displays the string in a message box. The program uses the MessageBox method imported from the User32.dll library.

Using System;  Using System.Runtime.InteropServices;  Class MainClass   {    [DllImport ("User32.dll")] public    static extern int. int MessageBox (int h, string m, string C, in t type);    hovertree.com  static int Main ()     {        string myString;         Console.Write ("Enter Your message:");        myString = Console.ReadLine ();        Return MessageBox (0, myString, "My Message Box", 0);    }  }

This example uses a C program to create a DLL, which is called from a C # program in the next example.

[CPP]
CMDLL.C   Q//compile with:/ld  int __declspec (dllexport) samplemethod (int i)  {    return i*10;  

The example uses two files CM.cs and cmdll.c to illustrate extern. The C file is an external DLL created in Example 2, which is called from within a C # program.

[C-sharp]
Cm.cs  using System;  Using System.Runtime.InteropServices;  public class MainClass   {    [DllImport (' Cmdll.dll ')] public    static extern int SampleMethod (int x);    hovertree.com  static void Main ()     {        Console.WriteLine ("SampleMethod () returns {0}.", SampleMethod (5));    }  

Output

SampleMethod () returns 50.
To build the project:
Use the Visual C + + command line to compile the cmdll.c to dll:cl/ld cmdll.c use the command lines to compile CM.CS:CSC CM.cs This will create the executable file CM.exe. Run this process

, SampleMethod passes the value 5 to the DLL file, which multiplies this value by 10 and returns the extern "C"
extern "C" contains a double meaning, literally: First, the object it modifies is "extern", and secondly, the target it modifies is "C". Let's take a detailed reading of this twofold meaning.

(1) The function or variable defined by extern "C" is an extern type;

extern is a keyword that indicates the scope (visibility) of functions and global variables in the C/s + + language, which tells the compiler that its declared functions and variables can be used in this module or in other modules. Remember, the following statement:

extern int A;

is simply a declaration of a variable that does not define variable A and does not allocate memory space for a. Variable A can only be defined once in all modules as a global variable, or a connection error occurs.

Typically, the function and global variables that this module provides to other modules in the header file of the module are declared with the keyword extern. For example, if module B is to reference the global variables and functions defined in module A, only the header file of module A can be included. In this way, when a function in module A is called in Module B, in the compile phase, Module B cannot find the function, but it does not error; it will find this function in the target code generated from module a during the connection phase.

Instance:

[CPP]
CppExample.h    #ifndef module_a_h  #define MODULE_A_H  extern int foo (int x, int y);//Declaration function, which is extern type  # endif    //////////////////////////////////////////////////////////////////////////////////////////////    // Hovertree.com  ///////////////////////////////////////////////////////////////////////////////////////////// /    //cppexample.cpp    #include <iostream>  #include "cppExample.h"  using namespace std;    int foo (int x, int y)//function defining extern type  {  cout << x+y;  return 0;  }    //main.cpp    #include <iostream>   #include "cppExample.h"  using namespace std;    void Main ()  {  foo (5,6);//Function call  }    /////////////////////////////////////////////////////////// //////////////////////////////////////////


Here, there is a question: in fact, if the cppExample.h in the declaration of a global function int foo (int x, int y), And then call the Foo function in Main.cpp, which are all the same, can be compiled successfully, the function is successfully called, then what is the use of this extern, not superfluous?

    The keyword corresponding to extern is static, and the global variables and functions it modifies can only be used in this module. Therefore, a function or variable may not be modified by extern "C" only if it is used by this module.


(2) The variables and functions modified by extern "C" are compiled and concatenated according to the C language;
does not add the extern "C" declaration when the compile method
First look at C + + in the C-like function is how to compile.

As an object-oriented language, C + + supports function overloading, whereas programming language C is not supported. Functions are compiled in C + + with different names in the symbol library than in the C language. For example, suppose a function is prototyped as:


void foo (int x, int y);

The function is compiled by the C compiler in the symbol library with the name _foo, while the C + + compiler produces names like _foo_int_int (different compilers may generate different names, but all use the same mechanism, and the resulting new name is called "Mangledname"). _foo_int_int such a name includes the function name, function parameter number and type information, C + + is this mechanism to implement function overloading. For example, in C + +, the function void foo (int x, int y) is not the same as the symbol generated by the compilation of void foo (int x, float y), which is _foo_int_float.


Similarly, variables in C + + support class member variables and global variables in addition to local variables. The class member variable of the program that the user writes may have the same name as the global variable, and we use the "." to differentiate. In essence, the compiler, when compiling, is similar to the processing of the function and takes a unique name for the variable in the class, which differs from the name of the global variable named in the user program.

Connection method without extern "C" declaration
assume that in C + +, the header file for module A is as follows:
     

[CPP]
Module A header file moduleA.h    #ifndef module_a_h  #define MODULE_A_H  int foo (int x, int y);  #endif    reference the function in module B:    //module B implements file ModuleB.cpp  #include "moduleA.h"  foo (2,3);//hovertree.com

  

In fact, during the connection phase, the connector looks for symbols like _foo_int_int from the target file Modulea.obj generated by module A!
add extern "C" after the declaration of the compilation and connection mode
After adding the extern "C" declaration, the header file of module a becomes:

  

[CPP]
Module A header file moduleA.h    #ifndef module_a_h  #define MODULE_A_H  extern "C" int foo (int x, int y);  #endif  //hovertree.com

Foo (2,3) is still called in the implementation file of Module B, and the result is:

(1) When module a compiles the target code of Foo, it does not have special handling of its name and adopts the C language method;

(2) When the connector looks for foo (2,3) call for the target code of Module B, it looks for the unmodified symbol name _foo.

If the function in module a declares Foo to be an extern "C" type, and Module B contains an extern int foo (int x, int y), module B cannot find the function in module A, and vice versa.

Therefore, it is possible to summarize the true purpose of the extern "C" statement in one sentence (the birth of any grammatical feature in any language is not arbitrary and is driven by demand from the real world.) When we're thinking about a problem, we can't just stay in the language, ask why it's doing it, what the motive is, so we can understand a lot more in depth:

Two. Customary method of extern "C"

(1) in C + +, references to functions and variables in the C language, in the case of a C language header file (assuming cExample.h), the following processing is required:
  

[CPP]
extern "C"  {  #include "cExample.h"  }  


In the header file of the C language, only the extern type is specified for its external function, and the extern "C" declaration is not supported in the C language, and a compile syntax error occurs when the. c file contains the extern "C".

The author of C + + reference C Function Example project contains the source code of the three files as follows:

[CPP]
/* C Language header file: cExample.h *    /#ifndef c_example_h  #define C_EXAMPLE_H  extern int add (int x,int y);  #endif    /* C language Implementation file: CEXAMPLE.C *    /#include "cExample.h"  int Add (int x, int y)  {  return x + y  ;  }    //C + + implementation file, call Add:cppFile.cpp  //The following paragraph can be replaced by extern "C" int foo (int x, int y);        extern "C"      {  #include "cexample.c"  }        //replace end  hovertree.com  int main (int argc, char* arg  V[])  {  Add (2,3);  return 0;  }  


If C + + calls a. dll written in C, the extern "C" {} should be added when the header file for the. dll is included or the interface function is declared.

(2) When referencing functions and variables in the C + + language, the header file of C + + must be added extern "C", but the header file that declares extern "C" cannot be directly referenced in C, only the extern "C" defined in C + + should be The function is declared as an extern type.

The author of the C-referenced function example of the three files in the project contains the following source code:

[CPP]
C + + header file cppExample.h  #ifndef cpp_example_h  #define CPP_EXAMPLE_H  extern "C" int Add (int x, int y);  #endif    //---------------------------------------------------------//    //c++ implementation file CppExample.cpp  # Include <stdio.h>  #include "cppHeader.h"  int Add (int x, int y)  {  return x + y;  }    ----------------------------------------------------------  #include <stdio.h>  /* C implementation file CFILE.C/ * This compiles an error: #include "cExample.h"  *  /extern int Add (int x, int y);    int main ()  {  int a = Add (2,3);  return 0;  }   Hovertree.com

Transferred from: http://hovertree.com/h/bjaf/1iogox2j.htm

Http://www.cnblogs.com/sosoft/p/timu.html

 

C # keyword extern usage

Related Article

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.