Statistics
16
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2026-01-03
Support
Share

AuthorMustafif Khan

No description

Tags
No tags
Publisher: BPB Publications
Publish Year: 2023
Language: 英文
File Format: PDF
File Size: 2.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
(This page has no text content)
Rust for C++ Programmers Learn how to embed Rust in C/C++ with ease Mustafif Khan www.bpbonline.com
Copyright © 2023 BPB Online All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor BPB Online or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. BPB Online has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, BPB Online cannot guarantee the accuracy of this information. First published: 2023 Published by BPB Online WeWork 119 Marylebone Road London NW1 5PU UK | UAE | INDIA | SINGAPORE ISBN 978-93-5551-355-7 www.bpbonline.com
Dedicated to My beloved Parents: Yousuf Khan Fouzia Sultana & to my amazing family and friends for their support
About the Author Mustafif Khan is a Canadian student majoring in Financial Mathematics and minoring in Computer Science. Some of his hobbies are programming, gaming, and writing. He has been writing his books since he was a kid, with a few self- published poetry books in his catalog. His interest in programming began with his wish to write his own website. Soon after, Khan became interested in systems programming with his change to using Linux distributions. He has been programming Rust for the last three years and has learned a lot from books, documentation, and building projects, such as TexCreate (a LaTeX project creator) and TexCore (a library to write LaTeX using Rust types). Before Khan found Rust, he was writing projects in C++ and Golang, although after using Rust, he has not been able to go back except for C.
About the Reviewer Pooya Eimandar is the leader of PlayPod, the first cloud gaming in the Middle East. He has developed many games and real-time applications in C/C++ and Rust with GPU APIs, mostly Vulkan and DirectX. He is also the author and technical reviewer of quite a few books in the game development area. Moreover, he is Co-Founder and CTO at RivalArium cloud gaming. This work is dedicated to the brave and courageous people of Iran who have become the source of inspiration for many around the world. Let us amplify their voice, their message and their hope for a brighter future; Women, Life, Freedom!"
Acknowledgement There are a few people I want to thank for the continued and ongoing support they have given me during the writing of this book. First and foremost, I would like to thank my parents for their continuous support as an author and programmer. Secondly, I would like to thank my best friends Catherine Xiao and Diane Zaide, who have been there to encourage me whenever I would have writer’s block. They have given me continuous support when things would get stressful, and without them, I do not know how I would have been able to complete this book. My gratitude also goes to the team at BPB Publications. This is my first experience writing a book for a publisher and with the support from BPB, the experience was way less scary as it may have seemed. I am grateful for the opportunity given to me and the experience I was able to gain from writing this book.
Preface This book is a beginner to advance guide for the Rust programming language. Still, since Rust has a notoriously steep learning curve, we are targeting C++ programmers who can use their pre-existing knowledge to help learn Rust easier. In this book, we will go through how to write simple programs in Rust, look at different topics such as networking, concurrency, and metaprogramming, and to better align our goals with C++. We will also look at unsafe Rust and Foreign Function Interface (FFI) to integrate Rust into a C project and vice versa. A neat approach taken in this book is dedicated project chapters that will give you a better experience writing programs in Rust to better cram in the knowledge you will be learning. We will build things such as command line applications to desktop apps (GTK and Tauri) and also write a standard library in Rust for the toy language, Mufi, with a bytecode compiler written in C. This book is divided into 11 chapters. The first 6 are beginner to intermediate level, while the last 5 are more advanced topics containing more complex, messy code. Within the 11 chapters, there will be seven dedicated to Rust content and four chapters dedicated to building projects. Chapter 1 will cover an introduction to the Rust programming language and how we can use it and C++ to flatten the learning curve of the language better. We will look into the fantastic package manager Cargo to create applications, libraries, benchmarking, and testing. The goal of this chapter is to have the reader be able to write simple programs in Rust, so beginner topics like bindings, conditionals, loops, functions, and structures will be discussed as well as trying to understand Rust’s ownership model and what it means to borrow a value.
Chapter 2 will cover how to apply object-oriented concepts to structures and enumerations using implementations, traits and generics. These techniques will allow developers take full advantage of structures and enumerations while also being able to see how things such as bounded methods, polymorphism and templates in C++ can be translated into Rust easily. Chapter 3 will cover how to handle errors in Rust, whether it means to handle them gracefully or panic. We will see Rust’s dedicated types toward error handling, instead of using a try-and-catch method. While we will learn how to handle errors, and will also look into creating our custom error type that can be applied in your projects for personalized error handling, which becomes a big part of a Rust project. Chapter 4 will cover how to create a command-line interface application in Rust using the amazing structopts crate. We will also learn how to write a simple web server so we can have our CLI act as the client, which will involve an introduction to asynchronous programming in Rust. After we create our application, we will go through the process of publishing it using the package manager Cargo. Chapter 5 will cover how to create concurrent programs in Rust using a combination of threads, smart pointers and locking types. We will discuss the importance of concurrency and how Rust guarantees thread safety in programs to avoid data races with the Send and Sync traits. Chapter 6 will cover the basics of networking in Rust in both synchronous contexts using the standard library and asynchronous contexts with the tokio crate. We will look into both kinds of contexts by creating IO models that can help us understand how to bind an address as well as reading/writing to data streams. Chapter 7 will cover how to create desktop applications for native Linux systems using the GTK framework. We will discuss the pros and cons on developing desktop applications using
Rust types exclusively and how to write different type of applications using the family of GTK crates. Chapter 8 will cover what unsafe Rust is and how to integrate other languages in a Rust program; our focus will be C/C++ using Rust FFI. We will discuss what it means to be safe and unsafe in Rust, and when it is appropriate to consider performing an unsafe operation. After discussing unsafe operations, we will look at adding raw C bindings to our Rust programs and using a Rust shared library in a C program. Chapter 9 will cover metaprogramming in Rust and how to utilize Rust syntax and token trees to generate code. We will discuss when it is appropriate to use metaprogramming compared to normal functions, traits, among others, and whether to choose declarative or procedural macros. Chapter 10 will cover how to integrate Rust into a bytecode- compiled toy language written in C called Mufi. In this chapter, we will look into developing a standard library in Rust for the language Mufi and creating a batch benchmark using native functions written in C, Rust, and an interpreted Mufi program. Chapter 11 will cover how to write cross-platform desktop applications using the Tauri framework. Like developing applications in GTK, we will look at the pros and cons of Tauri development and when to consider using it to create an application. We will discuss using Rust alongside a Svelte frontend to create responsive applications that functionally work similarly to Electron.
Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/dj5r16a The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/Rust-for-C-Plus-Plus- Programmers. In case there's an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family.
Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at: business@bpbonline.com for more details. At www.bpbonline.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on BPB books and eBooks.
Piracy If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at business@bpbonline.com with a link to the material. If you are interested in becoming an author If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions. We at BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com.
Table of Contents 1. Introduction to Rust Introduction Structure Objectives Installing Rust Getting started with Cargo Bin versus Lib Bindings and mutability Guessing game Ownership How Rust manages memory Owning and borrowing values Copy and clone Borrowing rules Rules Pointer types Control flow Logic operators Conditional operators If/Else Statements Match statements Loops While loops For loops Loop Statements Functions Declaring functions Modules and publicity Super versus self Testing and benchmarking Structs and Enums Structures Traditional C Struct
Tuple Struct Empty Struct Enumerations Conclusion Key facts Exercises Answers 2. OOP in Structs and Enums Introduction Structure Objectives From classes to structures Implementations Traits Deriving traits Type aliasing From templates to generics Generic structs Generic traits Conclusion Key facts Exercises Answers 3. Error Handling Introduction Structure Objectives Error Handling in C, C++, and Rust The Option<T> type The Result<T, E> type Converting a Result to an Option Creating a custom error type How could we improve? Conclusion Key facts
Exercises Answers 4. Project – Building a CLI App Introduction Structure Objectives Creating the base of the application A crash course in Async Creating the web server Creating the client Testing out the client How can we improve How to publish? Conclusion Key facts Exercises Answers 5. Concurrency in Rust Introduction Structure Objectives Smart pointers Heap-allocated values using box Reference counting using Rc & Arc Interior mutability using Cell and RefCell The importance of concurrency Implementing concurrency using threads Passing values using channels Using locking types to Write/Read bindings Single-threaded access using Mutex Multi-threaded reader using RwLock Conclusion Key facts Exercises Answers
6. Networking in Rust Introduction Structure Objectives The protocol stack Physical layer Data link layer Network layer Transport layer Application Layer Exploring the Net module Creating a synchronous IO model Testing using Redis Creating an asynchronous IO model The Future trait From Mio to Tokio How can we improve? Conclusion Key facts Exercises Answers 7. Project – GTK App Introduction Structure Objectives Setting up our GTK application Row data for our grocery list Storing rows into a model Assembling the final application Building the user interface Testing our GTK application Conclusion Key facts Exercises Answers
8. Unsafe Rust and FFI Introduction Structure Objectives Using the unsafe keyword Unsafe functions Unsafe traits Using C in Rust Using Rust in C Conclusion Key facts Exercises Answers 9. Metaprogramming Introduction Structure Objectives When to create macros? Declarative macros Creating a declarative macro Repetition Procedural macros Derive macros Attribute macros Useful attributes Function-like macros Conclusion Key facts Exercises Answers 10. Project – StdLib for Mufi Introduction Structure Objectives Getting started with Mufi-Lang
Declaring variables in Mufi Control flow in Mufi Loops in Mufi Functions in Mufi Classes in Mufi Inheritance in Mufi Creating native functions in C Creating native functions in Rust Benchmarking C versus Rust native functions Conclusion Key facts Exercises Answers 11. Project – App in Tauri Introduction Structure Objectives Getting started with Tauri Systems dependencies Hello World in Tauri Getting familiar with Svelte Overview of the application Creating the application More with Tauri Error handling Nesting each loops Challenges with Tauri development Conclusion Key facts Exercises Answers Index
The above is a preview of the first 20 pages. Register to read the complete e-book.