Calling C + + from Golang with swig--windows DLL II

Source: Internet
Author: User

Name mangling && name demangling

In the narrative GolangHow to useSwigcalledWindows DLLsbefore, you need to understand a concept:Name mangling (or calldecorated Name).input in Baidu translationName mangling, translated into Chinese is "name adaptation", or "name reorganization". decorated Name, is the name of Microsoft, Baidu translated into "decorated names." Whether it is the English name or the translated result,Name manglingthe term is more appropriate, and isC + +the general term in the field. Typically,C + +programmers don't need to knowName mangling, but generating or invoking a dynamic-link library within a project may require some understanding of it. Let's take a look at the following example.

Open VS2010,file--new-project, choose Visual c++--win32, select Win32 Console onthe right Application, create a project with a simple name

Click OK, then Next,

selected DLL, tick Export symbols, click Finish to finish creating.

The following is an auto-generated Simple.h file

The following ifdef block is the standard-of-the-creating macros which make exporting

From a DLL simpler. All files within this DLL is compiled with the Simple_exports

Symbol defined on the command line. This symbol should not being defined on any project

That uses the this DLL. This is the other project whose source files include the This file see

Simple_api functions as being imported from a DLL, whereas this DLL sees symbols

Defined with this macro as being exported.

#ifdef Simple_exports

#define SIMPLE_API __declspec (dllexport)

#else

#define SIMPLE_API __declspec (dllimport)

#endif

This class is exported from the Simple.dll

Class Simple_api Csimple {

Public

Csimple (void);

Todo:add your methods here.

};

extern Simple_api int nsimple;

Simple_api int fnsimple (void);

The automatically generated code exports a class, a function, a variable. Add a simple method to the Csimple class,SayHello

#ifdef Simple_exports

#define SIMPLE_API __declspec (dllexport)

#else

#define SIMPLE_API __declspec (dllimport)

#endif

This class is exported from the Simple.dll

Class Simple_api Csimple {

Public

Csimple (void);

Todo:add your methods here.

int SayHello ();

};

extern Simple_api int nsimple;

Simple_api int fnsimple (void);

CPP file:

This is a example of an exported variable

Simple_api int nsimple=0;

This is a example of an exported function.

Simple_api int fnsimple (void)

{

Return 42;

}

This is the constructor of a class which has been exported.

See Simple.h for the class definition

Csimple::csimple ()

{

Return

}

int Csimple::sayhello ()

{

return 0;

}

in the Add x64 in Configuration Manager

after compiling, the The main files generated by D:\Sample\Simple\x64\Debug are simple.dll,simple.lib,simple.pdb.

Typically, The C + + call DLL only needs to set additional library paths and additional dependencies in the project link properties to introduce Simple.lib, and the generation and invocation of the dynamic-link library will be over.

when calling the LoadLibrary and GetProcAddress interfaces, or resolving the runtime's lack of dynamic-link library issues, it often uses a well-known tool known to Windows developers dependency Walker, this tool can view the dependencies and import export functions, and open the 64-bit DLLs generated above with version x64.

In the export field, we see Simple.dll.exported the5functions (variables), function names are?Starting from the code, only the4Items:Csimpletwo member functions of a classCsimple::csimple,Csimple::sayhello,Fnsimpleand theNsimplevariables,Dependency WalkerThere are many exports in the1item, which can presumably be inferred from the function name, the fifth item isNsimplevariable, the fourth item isFnsimplefunction, and the third item isCsimple::sayhellofunction, the other two not too easy to see,One of them should beCsimple::csimple.

in the the VS installation directory (C:\Program Files (x86) \microsoft Visual Studio 10.0\vc\bin\amd64) has a few gadgets, one of which is called Undname.exe, The full name of this tool should be called undecorated Name , with decorated is antisense, this tool can parse the exported function name into a programmer's easy-to-read name. Call Undname in turn for 1-5

 

exported function name

Undname

[Email Protected]@[email protected]

"Public: __cdecl csimple::csimple (void) __ptr64"

[Email Protected]@[email protected]@@z

"Public:class Csimple & __ptr64 __cdecl csimple::operator= (class Csimple

Const & __PTR64) __ptr64 "

[Email protected]@ @QEAAHXZ

"Public:int __cdecl Csimple::sayhello (void) __ptr64"

[Email protected] @YAHXZ

"int __cdecl fnsimple (void)"

[Email protected]@3ha

"Int Nsimple"

The csimple::csimple () member function name has been processed by the compiler into [email protected]@[email protected],Csimple::sayhello The member function has been processed by the compiler into the [email protected]@ @QEAAHXZ, which is popularly said to be name mangling.

citing a foreign friend post in three paragraphs in English, although unofficial explanations, but personally think he put Name mangling clearly understood. If you want a more rigorous explanation, check Wikipedia yourself.

 here is a quick reminder on what's name mangling and why it's used in C + +. When an executable was started, some (many) of its symbols addresses was resolved during the Startup-at Runtime-because These addresses is isn't known during the static link (i.e. when the executable was generated). One-to-resolve them is-to-search them by symbol name. This was typically what was done when "Dlsym" was used, but it was also how the runtime linker resolves the address of the Ctions implemented in the dynamic libraries.

when developing in C, all public symbols of a executable are unique. It is not a possible to having a different variables or functions with the same name. The only exceptions to this is the local variables and static variables/functions. However such symbols is private to a function or a file and cannot is retrieved by name at runtime. So-C The symbols signature is the name of the appears in the code. The linker can find a function by using its name as the signature.

Things is not this simple in C + +. The symbols names cannot just be the name of the functions or methods because the language allows Polymorphism:a method c An has several prototypes to operate on different kinds of data. For example it was possible to declare "void foo (int)" and "void Foo (double)". In this case it isn't possible to use the function name as a signature without a conflict. This is what name mangling is Used:some additional information are added to the symbol name to make it unique in the Execut Able/library. One can see C + + mangling as a concatenation of the method name with its parameters types. This was a simplification because other things was used to generate a mangled name, but it was the general idea. Once names is mangled, it's possible to resolve symbols at runtime by name without conflict.

A simple translation is: C + + allows for function overloading, and name mangling is required to ensure that the names are unique. The C + + Standard does not have a clear name mangling rule, each compiler implementation is not the same, and even different versions of the same compiler, the same compiler on different platforms implementation, Name mangling may not be the same. (Refer to wiki Name mangling).

the more common twoC++compilers areGNU gcc (g++)compilers and MicrosoftVisual C + +compiler, these two compilersName manglingthe results are completely different. GNUThe compiler is open source, so itsName manglingthe rules and codes can be found on the Internet. github.comon thegcc-mirror/gcc,gcc/gcc/cp/mangle.cis aGCCcompilerName manglingpart of the source code.

Visual C + + is a commercial closed source software, his name mangling rules are nonpublic, Microsoft's terminology is called decorated name, the official information is very poor, You can View relevant content on MSDN.

the Name mangling After a preliminary understanding, we continue to look at the example. Compile the VS2010 Auto-generated code above with g++ into a DLL file.

before compiling, you need to install tdm-gccin Windows OS, which is a Windows for the GCC compiler version of the implementation, the official ( Http://tdm-gcc.tdragon.net/download ).

in theD:\Sample\Create subfolders under FoldersGCCand WillSimple.hand theSimple.cppCopy files toD:\SAMPLE\GCCNext, you willSimple.cppin the file#include "stdafx.h"comment out. Open the command line and switch toD:\SAMPLE\GCC, performg++-shared-wall-o Simple.dll simple.cpp-dsimple_exports, generating aSimple.dll, again withDependency WalkerOpen the newly generatedSimple.dll

at first glance,Gcccompiled byDLLalso exports the5a function (variable), in fact, the third and fourthEntry Pointsame, the same function has two names. GNU C + +The compiler also has a tool namedc++filt, his features and Microsoft'sUndname.exeis the same, yes.Mangled namemakedemangling. In turn ,1-5calledc++filt

Mangled names

C++fi Lt

_z8fnsimplev

FnS Imple ()

_zn7csimple8sayhelloev

Csimple::sayhello ()

_zn7csimplec1ev

Csimple::csimple ()

_zn7csimplec2ev

Csimple::csimple ()

nsimple

nsimple

Visual c++ compiler and Span style= "FONT-FAMILY:CALIBRI;" >gnu compiler name mangling Span style= "font-family: the song Body;" The result is completely different, and the demangle c++filt

Both Microsoft and GNU compilers provide demangling Tools during the demangling process, but if you want to use a tool from a Name Get Mangled Name , as if there is no separate tool, according to my Baidu plus Google results to the answer. However, the results can be obtained indirectly by using compiler preprocessing, which is given in a later essay.

As you can see from the first example above,the vs2010 C + + compiler automatically generates a copy assignment operator for the Csimple class =, as seen in the third edition of effective C + +, we know that article 5, "Understanding C + + default writing and calling which functions", says: " When was empty class (empty) no longer an empty classes? After C + + has processed it. Yes, if you do not declare yourself, the compiler declares a copy constructor for it (compiler version), a copy assignment operator, and a destructor. In addition, if you do not declare any constructors, the compiler will also declare a default constructor for you. All of these are public tangent inline. Again, "only when these functions are needed (called) will they be created by the compiler." ”

when generating a dynamic-link library, the Microsoft compiler does not seem to comply with clause five, because when the DLL file is generated, the compiler cannot know whether the caller of the DLL invokes the copy assignment operator; the gun compiler complies with this clause, Only constructors Csimple::csimple () and Csimple::sayhello () are in the exported class member function. Or, clause Five describes the behavior of the GNU C + + compiler.

Calling C + + from Golang with swig--windows DLL II

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.