Write c ++ as a script language!

Source: Internet
Author: User

When talking about the script, my mind immediately flashed a lot: Python, Perl, Ruby, PHP, JS, vbs, Lua... But have you ever heard of it, using the classic C ++ as a scripting language? Let's not talk about it more. The previous figure. (Don't tangle with that function. It's just a macro. You'll understand it later)

  

  

  

Maybe you may think this is crazy. You can use the most complex language in the world to make scripts. If the writing staff is tired, the script engine is exhausted first. A variety of complex template libraries must be interpreted and run. how powerful a virtual machine can survive.

Well, let's take a step back. We don't need to force the explain execution, and we will return to the original compilation and then execute it. ---- But is that a script?

  

Compilation speed

In fact, nowadays, high-performance scripts are compiled and run first. The famous JavaScript V8 engine is called LUA-jit, the fastest speed, and well-known ActionScript... Pre-compilation not only greatly improves the running speed, but more importantly, it can detect explicit errors in the script in advance.

  

However, the so-called compilation in scripts and the compilation of traditional languages are quite different. Script compilation is just a deep optimization of the code and can be completed soon. Compared with the complicated C ++, it seems to be far from satisfactory. When it comes to the compilation speed of C ++, everyone's image is not as slow as pressing F5 in VC and looking at the "compiling..." in the output box. Sometimes it takes several seconds to test a small modification. The slow Compilation speed is so hard that simple programs often choose VB or C #, which can be quickly debugged.

  

For a large MFC program, slow compilation is a matter of course. However, if a simple small program has a long Compilation Time, it must be unreasonable to reference the header file. In fact, the compilation of small programs that use pre-processing header files is only an instant, and various pauses are often caused by IDE.

  

Then let's test it. Instead of using IDE, we can only compile a C ++ applet with pure commands. We use the vc6.0 compiler cl.exe.

To ensure a clean compiling environment, copy the files that cl.exe must depend on to the new folder. For vc6's example, you only need to have 5 files to complete. cppto. EXE compilation.

Cl.exe
C1xx. dll
C2.dll
Mspdb60.dll
Link.exe

Open CMD and set the environment variables, corresponding to the vc6 header directory and library directory.

Set include = c: \ Program Files (x86) \ Microsoft Visual Studio \ vc98 \ include

Set Lib = c: \ Program Files (x86) \ Microsoft Visual Studio \ vc98 \ Lib

You can call the command to compile:

CL test. cpp

In the twinkling of an eye, the engineer compiled and completed the link and generated test.exe. Everything is normal. This is compiled without the pre-compilation header.

  

It can be seen that, even if the language itself is very complex, as long as the code written with it is not complex, compilation is still very fast.

Think about it. With today's hardware configuration, a 98-year compiler is used to compile a program with only a few lines of code.

The command line compilation of a simple C ++ program is so fast that we can continue to explore the script with this advantage...

  

Running Environment

If you want to write a small program that generates 100 random serial numbers, what languages do you use?

Compared with traditional languages, we need to create a project first, so we can directly create a text file on the desktop to write scripts.

Although writing code with a text editor does not have any advantages, it is sufficient for simple programs. When the program is handed over to others for use, the script advantages are fully reflected: when they want to modify some logic rules, they only need to open it in notepad, the notepad is available on every computer.

On the contrary, even if a program written in a traditional language has source code, it cannot take effect after a simple modification. You still need to install and configure the corresponding development environment, this is a great deal for unfamiliar people.

  

Therefore, the script must be simple enough-you only need to modify and run the script, and other steps are automatically completed by the Script Host.

  

If you want to use C ++ to write scripts, the code compilation and links must be fully automated, which is not complicated.

However, it is still not enough to rely on cl.exe and other commands, because there is no corresponding development environment on other computers-include and Lib folders, so compilation and linking are impossible.

These header file libraries contain up to thousands of files, all of which carry nearly MB! Obviously, our scripts only use a few basic functions, and complicated windows header files are unnecessary.

  

In fact, the header file of the program is just the definition of functions and structures. It is only used for analysis by the compiler and does not generate actual commands. Therefore, we generate a common header file in advance.. PCH pre-compiled HeaderFile. After compilation, You can map it to a header file, such as stdafx. h. In this way, no header file is required. Even if stdafx. H doesn't exist, compilation still works, because it is packaged in. PCH. A large number of header files are analyzed in advance, so they do not need to be compiled during compilation, greatly improving the speed.

  

The LIB file contains the library function content. Unless the entire program does not use any C Runtime Library, we can not carry any Lib, but it can only write the most basic code. For general simple script programs, only a few necessary Lib is required:Kernel32.lib, libcmt. Lib, libcpmt. Lib, oldnames. Lib. A total of more than 1 m.

  

We put these libfiles in the same directory as the. pchfile and cl.exe, so that we do not need to specify the include and Lib environment variables.

  

  

So far, we have a lite version of The vc6 compiler. With the above 10 files, we can compile C ++ programs independently without any environment.

CL/YU "stdafx. H"/FP "mydll. PCH" test. cpp

Actual Operation

Now, we can dynamically generate C ++ code files and automatically compile the files. But how can we interact the final binary file with the Script Host?

Because EXE can only run in an independent process, data interaction can only be performed through an anonymous pipeline, it is very difficult to implement callback or anything.

However, if you replace it with a DLL, you will be able to demonstrate your skills, not only to run in the same process space, but more importantly, dll can be dynamically loaded and detached, which is too consistent with the features of the script program. When a module is updated, you can release the previous module and load the latest one. All of this is dynamic and can be done without restarting the host!

In addition, the DLL can export internal functions. The host can use getprocaddress () to easily obtain a function address. For callback, pass a host function pointer to the script. As long as the function declaration is agreed, both parties can call each other using the simplest and original method, or even share the same memory space.

  

To make function export more concise, this example definesFunctionMACRO:

#define function extern "C" __declspec(dllexport) void

So you can simply define an export function:

function Test(){      // some code here}

Is it very script-like :)

  

Syntax check

A spelling mistake is inevitable for a code typed in a text editor. Therefore, a good script engine performs a comprehensive syntax check before running, excluding obvious errors in advance, rather than running while interpreting.

C ++ achieves the limit, not only can identify fatal errors, but even non-standard code also has a warning. This is very worthwhile. A small bug wastes tens of thousands of times of compilation.

It is actually very simple to implement this function in our c ++ script. This is because when cl.exe is used for compilation, any compilation error will be reported. We will prompt the user based on the corresponding error line number.

  

  

  

 
Debugging environment

A powerful Script Engine often comes with a debugger. Although the compiler can exclude some errors in advance, logical errors can only occur at runtime.

For simple script programs, this function does not seem so important. After all, running in the debugging status may affect the performance.

In the C ++ script, we can use a macro to expand the debugging function and decide whether to output the debugging information. However, the handling of exception errors is more important.

Since we finally run the binary DLL module, it is quite different from the normal script. The DLL module shares a process with the host. Therefore, when an exception occurs in the DLL, the entire process, including the host, enters the debugging status (if the system is equipped with a development environment ). If the error is too serious, the entire process will crash. This is worth noting, and it is also a hidden danger in the permission of C ++ scripts. Therefore, use less pointer features and safer code to minimize code risks.

For fatal errors, it is very important for the host to record the dump file for debugging.

  

However, for simplicity, in this example, the host is written in VB, so it is impossible to use _ Try {} For seh capture before calling. If the host is also implemented in C ++, capture exceptions in the DLL as much as possible.

 

Development Environment

Different from the scripting language, C ++ itself is used for the development of large programs, so the development environment is very complete.

But as a script, it is often a single text file, rather than a project team. Editing a single CPP file in any version of VC is almost the same as editing a plain text file. Therefore, we have to create a template project in advance and move the CPP to be edited to be developed in this project so that there will be smart prompts and other functions in the drop-down box.

However, since it is used as a script, it should be used to handle some simple and frequently changed logical transactions. For complex script programs, it is better to write them directly in the host.

  

In fact, there is no fixed line between "programs" and "scripts. A pure program can also be used to write a complex game story, and a large project can be developed with pure scripts. However, being too rigid or too flexible will increase the workload.

 

Summary

Rather than C ++ scripts, It is a plug-in that dynamically generates commands as needed.

Although some script features can be transferred out, C ++ is a strict language. Compared with the flexibility of scripts, C ++ is more rigorous and rigid. Of course, with powerful macros, templates, and operator overloading, we can fully expand to provide a variety of features and syntactic sugar for the script.

Of course, its advantages are also obvious: high performance, simple interaction. And fully supports the features of C ++.

  

  

In fact, more than just C ++, any advanced language can be used as a "script", as long as it calls their compiler. If you like C # or Java style, you only need to make a slight modification.

 

For simple demonstration, this example uses VB to write a simple Host Program, including basic compilation, linking, loading, and syntax check functions.

The host provides an interface called "print" to output strings. To implement more interfaces and extensions, modify the T. h In the CL folder.

  

Source code can be downloaded here: http://files.cnblogs.com/index-html/CppScript.rar

  

There is a dlltmpl project, which is useless, just to generate a. PCH pre-compiled header file. If you want to use more header files in the script, you must add them in stdafx. h. Copy the compiled release/mydll. pch to the Cl folder and overwrite the original one.

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.