C++ Builder

Learn How To Use Return Type Deduction In C++ For Windows Apps

In this tutorial, you will learn how to use return type deduction in C++ Builder. For the C++14 scheme of auto with functions, the compiler can deduce return types for any function, no matter how complex it is. The only requirement is that each return statement needs have the same type. The practices are identical as for auto variables. To deduce the type, the compiler requires to detect the function definition right ahead. That means this technique is limited to function templates, inline functions, and helper functions which are applied only inside a particular translation unit. Here is a code example on return type deduction #ifdef _WIN32 #include #else typedef char _TCHAR; #define _tmain main #endif #include #include class employee { // Lots of code here }; struct person_id { std::string first_name; std::string last_name; }; class employees { public: auto find_employee(const std::string& name) { return 1; } }; int return_an_int() { return 1; } auto return_something() { return 1; } // The following will give a compiler error, because int and // float are different types //auto returnConfusion() { // if (std::rand() %2 == 0) { // return -1; // } else { // return 3.14159; // } //} int main() { auto i{ return_an_int() }; auto j{ return_something() }; // Example of a method with multiple return points, each with different types – an error // auto k {returnConfusion()}; auto employee_list{ std::make_unique() }; auto person = employee_list->find_employee(“Jane Smith”); system(“pause”); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 #ifdef _WIN32 #include #else typedef char _TCHAR; #define _tmain main #endif   #include #include   class employee {     // Lots of code here };   struct person_id {     std::string first_name;     std::string last_name; };   class employees { public:     auto find_employee(const std::string& name) { return 1; } };   int return_an_int() {     return 1; }   auto return_something() {     return 1; }   // The following will give a compiler error, because int and //     float are different types //auto returnConfusion() { //    if (std::rand() %2 == 0) { //        return -1; //    } else { //        return 3.14159; //    } //} int main() {     auto i{ return_an_int() };       auto j{ return_something() };       // Example of a method with multiple return points, each with different types – an error     // auto k {returnConfusion()};       auto employee_list{ std::make_uniqueemployees>() };       auto person = employee_list->find_employee(“Jane Smith”);       system(“pause”);     return 0; } So, return type deduction bypasses undesirable conversions and the removes type changes you must to apply. If there is a possibility to use return type deduction, just apply this technique. Because this can assist to secure the types you utilize more consistently. Check out more modern C++ features over here on GitHub

Read More

Manual uninstall of RAD Studio/Delphi/C++Builder 10.4 Sydney

Launch the License Manager from the bin folder (by default “C:Program Files (x86)EmbarcaderoStudio21.0binLicenseManager.exe”) and delete any trial or beta (Test Field) license that you can find. Check it under “License Details” in the center column. Under your Control Panel’s Program and Features Add/Remove Program uninstall the following entries: RAD Studio 10.4 version 21.0 Please follow these instructions to remove any leftover files:     If Windows 64-bit, remove the C:Program Files (x86)EmbarcaderoStudio21.0 directory (or the custom folder you had used).    Remove the C:UsersPublicDocumentsEmbarcaderoStudio21.0 directory    Remove the C:ProgramDataEmbarcaderoStudio21.0 directory.    Remove the %APPDATA%EmbarcaderoBDS21.0 directory.    Remove the HKEY_CURRENT_USERSOFTWAREEmbarcaderoBDS21.0 registry key    If Windows 64-bit, remove the HKEY_LOCAL_MACHINESOFTWAREWow6432NodeEmbarcaderoBDS21.0    If Windows 64-bit, remove the following files from C:WindowsSysWOW64:        BDEAdmin.*        CC32*.DLL        Midas.*        Xerces*.DLL Field testers should also do the following (and others may want to as well):     Delete the Godzilla license from License manager before uninstalling it or during the installation of RAD Studio 10.4 Sydney If you had problems in the second step (uninstalling from Windows Control Panel), try this Microsoft tool to solve un-installation problems: http://go.microsoft.com/?linkid=9779673

Read More

Easily Create A Python Container Type In Delphi And Execute It In This Windows Sample App

Earlier we learned how to create a Python type using Delphi classes. How about creating a Python type with some containers or collections capabilities in Delphi and accessing its elements? Python4Delphi PyObject contains Type Services routines e.g Basic, Number, Sequence, Mapping which can be overridden with our custom Python Types Delphi classes. This post helps to do that. Python4Delphi Demo27 Sample App shows how to create a Module, Python type, Import the module, and Python Type in a python script, create a sequence type object and access some of the service routines like length, indexing, etc. You can find the Demo27 source on GitHub. Prerequisites: Download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out this video Getting started with Python4Delphi. Components used in Python4Delphi Demo27 Sample App: TPythonEngine: A collection of relatively low-level routines for communicating with Python, creating Python types in Delphi, etc. It’s a singleton class. TPythonGUIInputOutput: Inherited from TPythonInputOutput (which works as a console for python outputs) Using this component Output property you can associate the Memo component to show the Output. TPythonModule: It’s inherited from TMethodsContainer class allows creating modules by providing a name. You can use routines AddMethod, AddMethodWithKW, AddDelphiMethod, AddDelphiMethodWithKeywords to add a method which should be type compatible with this routine parameter. You can create events using the Events property. TPythonType: This component helps to create a new python type in Delphi which is inherited from the hierarchy of classes (set of APIs to create, manage methods, and members). TMemo: A multiline text editing control, providing text scrolling. The text in the memo control can be edited as a whole or line by line. You can find the Python4Delphi Demo27 sample project from the extracted repository ..Python4DelphiDemosDemo27.dproj. Open this project in RAD Studio 10.4.1 and run the application. Implementation Details: PythonEngine1 provides the connection to Python or rather the Python API. This project uses Python3.9 which can be seen in TPythonEngine DllName property. PythonGUIInputOutput1 provides a conduit for routing input and output between the Graphical User Interface (GUI) and the currentlyexecuting Python script. PythonModule1 with a Module name test is created. In this sample, Created a Delphi class(TMySeq) implementing a new Python type. It is derived from TPyObject. It overrides some Mapping services virtual methods such as MpLength, MpSubscript. function TMySeq.MpLength: NativeInt; begin Result := 10; end; function TMySeq.MpSubscript(obj: PPyObject): PPyObject; begin Result := obj; GetPythonEngine.Py_XINCREF(obj); end; function TMySeq.MpLength: NativeInt; begin   Result := 10; end;   function TMySeq.MpSubscript(obj: PPyObject): PPyObject; begin   Result := obj;   GetPythonEngine.Py_XINCREF(obj); end; During PythonType1 initialization assign the property PyObjectClass with the class TMySeq. procedure TForm1.PythonType1Initialization(Sender: TObject); begin with Sender as TPythonType do PyObjectClass := TMySeq; end; procedure TForm1.PythonType1Initialization(Sender: TObject); begin   with Sender as TPythonType do     PyObjectClass := TMySeq; end; On Clicking Execute Button the below code is executed. procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings(Memo2.Lines); end; procedure TForm1.Button1Click(Sender: TObject); begin   PythonEngine1.ExecStrings(Memo2.Lines); end; Which will execute the python script mentioned below. import test S=test.CreateMySeq() print (S) print (len(S)) print (S[1]) print (S[1,2]) print (S[1:2]) print (S[1:20:2]) print (S[…]) print (S[1,4,5:8, 10:20:2, …]) import test S=test.CreateMySeq() print (S) print (len(S)) print (S[1]) print (S[1,2]) print (S[1:2]) print (S[1:20:2]) print (S[…]) print (S[1,4,5:8, 10:20:2, …]) Note. CreateMySeq in the above script is created automatically by Python4Delphi when the property GenerateCreateFunction of TPythonType1(MySeq) is true. Python4Delphi Demo27

Read More

Quickly Learn How To SubClass A Python Type Created In Delphi With This Windows Sample App

import spam   class MyPoint(spam.Point):   def Foo(Self, v):     Self.OffsetBy(v, v)   # old way to create a type instance p = spam.CreatePoint(2, 5) print (p, type(p)) p.OffsetBy( 3, 3 ) print (p.x, p.y) print (“Name =”, p.Name) p.Name = ‘Hello world!’ print (“Name =”, p.Name)   # new way to create a type instance p = spam.Point(2, 5) # no need to use CreateXXX anymore print (p, type(p)) p.OffsetBy( 3, 3 ) print (p.x, p.y)   # create a subtype instance p = MyPoint(2, 5) print (p, type(p)) p.OffsetBy( 3, 3 ) print (p.x, p.y) p.Foo( 4 ) print (p.x, p.y) print (dir(spam)) print (spam.Point) print (“p = “, p, ”  –> “,) if type(p) is spam.Point:   print (“p is a Point”) else:   print (“p is not a point”) p = 2 print (“p = “, p, ”  –> “,) if type(p) is spam.Point:   print (“p is a Point”) else:   print (“p is not a point”) p = spam.CreatePoint(2, 5) try:   print (“raising an error of class EBadPoint”)   p.RaiseError() # it will raise spam.EBadPoint except spam.PointError as what: # this shows you that you can intercept a parent class   print (“Caught an error derived from PointError”)   print (“Error class = “, what.__class__, ”     a =”, what.a, ”   b =”, what.b, ”   c =”, what.c)   # You can raise errors from a Python script too! print (“——————————————————————“) print (“Errors in a Python script”) try:   raise spam.EBadPoint(“this is a test!”) except:   pass   try:   err = spam.EBadPoint()   err.a = 1   err.b = 2   err.c = 3   raise err except spam.PointError as what: # this shows you that you can intercept a parent class   print (“Caught an error derived from PointError”)   print (“Error class = “, what.__class__, ”     a =”, what.a, ”   b =”, what.b, ”   c =”, what.c)   if p == spam.CreatePoint(2, 5):   print (“Equal”) else:   print (“Not equal”)

Read More

Easily Add Slide Animations To Your Cross Platform Apps With Gesture Support In This FireMonkey Sample

In this post, you will discover two different demo application, the first one shows you how to add sliding tabs to an application through the use of multiple tabs with custom settings, next and back buttons, and gesture support. The second sample shows you how to implement a master-detail interface and display the Multiview control as a slide-in drawer, popover menu, docked panel, and more. What can you learn? Tab Control Input Form Creation Gestures Animation and managing the form with custom functions You can get these demo application from GetIt! Be sure to check out more sample applications in GetIt here!

Read More

Boost Productivity With Useful Bookmarks IDE Plugin To Bookmark And Navigate Code In Delphi And C++Builder

Many know how to use BookMark in your code editor using the RAD Studio IDE. You can mark a location in your code with a bookmark and jump directly to it from anywhere in the file. Bookmarks are preserved when you save the file and available when you reopen the file in the Code Editor. These existing IDE Bookmark features can be replaced with a flexible IDE Plugin Bookmarks 1.6.2. This post will help to understand more about this plugin. This is applicable for Delphi/C++ Builder. Overview of the BookMark1.6.2 As we know existing IDE Code editor has a bookmark feature, where a user can book mark up to 10 bookmarks and easily navigate to the code. This same feature is Replaced with an elegant Bookmark Icon and with some more shortcuts like auto numbering the Bookmark by short cut key (ctrl+B). Jump between the markers quickly by pressing (ctrl+ Alt+ Left or Right Arrow) keys. Never overwrite an existing bookmark accidentally. How to install: You can easily install this IDE Plugin from GetIt Package Manager. The steps are as follows. Navigate In RAD Studio IDE->Tools->GetIt Package Manager->select IDE Plugins in Categories-> BookMarks 1.6.2 by Embercadero Technologies and click Install Button. Read the license and Click Agree All. An Information dialog saying ‘Requires a restart of RAD studio at the end of the process. Do you want to proceed? click yes and continue. It will download the plugin and installs it. Once installed Click Restart now. BookMarks1.6.2 How to use: Open some projects in the IDE, place the cursor in some lines, and press Ctrl+B. A Bookmark Icon Popped with a Number and placed a marker. Like this, you can create 10 bookmarks. Beyond 10 Bookmarks it is marked as # instead of a number. You can press Ctrl + 1, Navigate to the first bookmark, press Ctrl + 2, and so on. For the 10th Bookmark, it is represented as 0 and the shortcut key is Ctrl+0. Beyond 10 Bookmarks, it can be marked as #. Jump between the BookMarks quickly with Ctrl+Alt+Left or Right Arrow. You can view/add/clear the bookmarks by clicking Menu View->Editor->BookMarks. View Bookmarks Be sure to check out all the available sample applications here! Find out more information about the Bookmarks plugin in Embarcadero GetIt.

Read More

Manage Your Collection Of Pages Easily With TCardPanel Component For Your Delphi VCL Application

We know TPanel  Control has methods to help manage the placement of child controls embedded in the panel. You can also use panels to group controls together, similar to the way you can use a group box. How about having a collection of cards or pages which help to manage the child controls and display only one of them at a time similar to a TabControl? Yes, Delphi provides an excellent VCL component TCardPanel. This post guide you to get TCardPanel sample Project from the GetIt Package manager. Overview of TCardPanel: TCardPanel allows you to display a collection of cards or pages (TPanel controls) that can be displayed one at a time. The control displays the active card and its content and you can write code to switch to any other card or use the integrated mechanism to let a user move among cards sequentially with a swipe gesture. A Card Panel hosts multiple subpanels displaying only one of them, similar to a TabControl, but it has no specific UI indicating the various panels. How to install TCardPanel Demo: You can easily install this Sample Project from GetIt Package Manager. The steps are as follows. Navigate In RAD Studio IDE->Tools->GetIt Package Manager->select Sample Projects in Categories-> Card Panel Demo(Delphi) 1.0 by Embercadero Technologies and click Install Button. Read the license and Click Agree All. An Information dialog saying ‘Requires a restart of RAD studio at the end of the process. Do you want to proceed? Click yes and continue. It will download the plugin and installs it. Once installed Click Restart now. GetIt Card Panel Demo Upon installation completion, it opens the sample project CardPanel. You can compile, and run the application. The source code is located in the location C:UsersPublicDocumentsEmbarcaderoStudio21.0SamplesObject PascalVCLCardPanel This Sample app contains a TCardPanel on the form with 5 cards placed with each contains an image component. On clicking the button Previous and Next the respective cards were navigated. for more details check this Docwiki. Check the TCardPanel Demo output here, TCardPanel Demo Be sure to check out all the available sample applications here! Find out more about the TCardPanel demo available via Embarcadero GetIt! Also available for C++Builder Windows apps in GetIt!

Read More

Learn To Use Python Objects Inside Your Delphi Source Code With This Windows Sample App

Sometimes we may need to use Python objects like COM automation objects, inside your Delphi source code. Thinking about how to do it? Don’t worry. Python4Delphi has an excellent library unit that does for us. Using this we just create python objects by passing values as a variant that will return the python type as Delphi variant type. Also, the library has extensive helper routines to validate the type as well. This post guide you to understand better using the Python4Delphi sample app. You can also use Python4Delphi with C++Builder. Python4Delphi Demo25 Sample App shows how to create a python variable type (i.e. Integer, Float, String, Dates, Mappings, Object types) in Delphi by just passing values as variant type parameters. You can find the Demo25 source on GitHub. Prerequisites: Download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out this video Getting started with Python4Delphi. Components used in Python4Delphi Demo25 App: TPythonEngine: A collection of relatively low-level routines for communicating with Python, creating Python types in Delphi, etc. It’s a singleton class. TPythonGUIInputOutput: Inherited from TPythonInputOutput (which works as a console for python outputs) Using this component Output property you can associate the Memo component to show the Output. TMemo: A multiline text editing control, providing text scrolling. The text in the memo control can be edited as a whole or line by line. VarPyth.pas – set of classes and helper routines to create python types and return variant types in Delphi. You can assert whether the type is Python type, Kind of python types(e.g. IsInteger, IsBool, IsFloat), etc. Also, you can use BuiltinModule routines to manipulate variant values. You can find the Python4Delphi Demo25 sample project from the extracted GitHub repository ..Python4DelphiDemosDemo25.dproj. Open this project in RAD Studio 10.4.1 and run the application. Implementation Details: PythonEngine1 provides the connection to Python or rather the Python API. This project uses Python3.9 which can be seen in TPythonEngine DllName property. PythonGUIInputOutput1 provides a conduit for routing input and output between the Graphical User Interface (GUI) and the currentlyexecuting Python script. In this sample app, We have Buttons which unit tests different python types in Delphi. This is achieved by routines in VarPyth.pas. some e.g mentioned below. VarPythonCreate – Create a python type in Delphi bypassing variant values as a parameter. Internally the python object type is created based on the value in the parameter and returns the variant. Using this in Delphi we can perform python arithmetic operations, string manipulations, sequence operations, etc with the help of VarPyth helper routines. Memo2, used for providing the Python Script to execute, and Memo1 for showing the output.  On Clicking Execute Button the python script is executed. On Clicking Run Selected tests once it will validate each type created and manipulates some arithmetic, string manipulations, etc. procedure TMain.btnTestIntegersClick(Sender: TObject); var a, b, c : Variant; big : Int64; begin // initialize the operands a := VarPythonCreate(2); Assert(VarIsPython(a)); Assert(VarIsPythonNumber(a)); Assert(VarIsPythonInteger(a)); Assert(Integer(a) = 2); b := VarPythonCreate(3); Assert(VarIsPython(b)); Assert(VarIsPythonNumber(b)); Assert(VarIsPythonInteger(b)); Assert(Integer(b) = 3); end; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 procedure TMain.btnTestIntegersClick(Sender: TObject); var   a, b, c : Variant;   big : Int64; begin   // initialize the operands   a := VarPythonCreate(2);   Assert(VarIsPython(a));   Assert(VarIsPythonNumber(a));   Assert(VarIsPythonInteger(a));   Assert(Integer(a) = 2);     b := VarPythonCreate(3);   Assert(VarIsPython(b));   Assert(VarIsPythonNumber(b));   Assert(VarIsPythonInteger(b));   Assert(Integer(b) = 3); end; Note : The […]

Read More

Learn To Build A Python GUI For Working with HTTP Requests With Requests Library In A Delphi Windows App

Python for Delphi (Python4Delphi , P4D) with Requests library allow you to execute Http requests in Python GUI for Windows. Python4Delphi is a free tool that can run Python scripts, work with new Python types and modules in Delphi. In this post, we will learn at how to run Requests library in Python for Delphi. Build your own Python GUI apps for Windows with Delphi and C++Builder and Python4Delphi using various Python libraries. Open and run project Demo1, then select Python script that you want execute in Python for Delphi. Use text fields for inserting Python script and for viewing results. Click Execute button for running Python script. Go to GitHub and download Demo1 source. procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings( Memo1.Lines ); end; procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings( Memo1.Lines ); end; Requests is a simple Python library that allows you to execute standard HTTP requests. Using this library, you can pass parameters to requests, add headers, receive and process responses, execute authenticated requests. Let’s look at some examples. Make GET Request It is very easy to call GET request. Just use method get() and pass URL to this method. From response object you can get a lot of useful information. This example shows how to get content, status and list of response headers. You also can get other properties. import requests r = requests.get(‘https://example.com’) print(r.text) print(r.headers) print(r.status_code) import requests r = requests.get(‘https://example.com’) print(r.text) print(r.headers) print(r.status_code) POST Request with payload and timeout With Requests library, you can perform post requests by calling post() method. It is also possible to pass input data to the parameter payload. Different types of input data are possible. For example, dictionaries, tuples, lists import requests payload1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’} r = requests.post(“https://httpbin.org/post”, data=payload1) print(r.text) payload2 = [(‘key1’, ‘value1’), (‘key1’, ‘value2’)] r1 = requests.post(‘https://httpbin.org/post’, data=payload2) print(r1.text) payload3 = {‘key1’: [‘value1’, ‘value2’]} r2 = requests.post(‘https://httpbin.org/post’, data=payload3) print(r2.text) import requests payload1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’} r = requests.post(“https://httpbin.org/post”, data=payload1) print(r.text)   payload2 = [(‘key1’, ‘value1’), (‘key1’, ‘value2’)] r1 = requests.post(‘https://httpbin.org/post’, data=payload2) print(r1.text)   payload3 = {‘key1’: [‘value1’, ‘value2’]} r2 = requests.post(‘https://httpbin.org/post’, data=payload3) print(r2.text) Authenticated Request In this example we will take a look at how to execute authenticated requests. It is very easy, just pass the username and the password in the auth parameter. If authorization is successful, then we will receive a response status code 200, otherwise there should be non-authorization error 404. import requests from getpass import getpass r=requests.get(‘https://test.org’, auth=(‘username’, getpass())) print(r.status_code) import requests from getpass import getpass r=requests.get(‘https://test.org’, auth=(‘username’, getpass())) print(r.status_code) Check out the Requests library for Python a use it in your own projects. Check out Python4Delphi which can build Python GUIs for Windows using Delphi.

Read More

Achieve High Performance By Using The string_view C++17 Feature In C++Builder

In this tutorial, you will learn another modern C++17 feature to work with strings. This feature is a std::string_view. The purpose of any kinds of string reference proposals is to bypass copying data that already owned someplace and of which only a non-mutating representation is required. The std::string_view is one such proposal. There was an earlier one named string_ref. The std::string_view is a picture of the string and cannot​ be utilized to alter the original string value. When a std::string_view is constructed, there’s no need to replicate the data. Besides, the std::string_view is smaller than std::string on the heap. How can you use std::string_view with C++ Builder? string_view lives in the header file Benefits of the string_view string_view is useful when you want to avoid unnecessary duplicates The creation of string_view from literals does not need a dynamic allocation. The following code illustrates how string_view supports save memory by restricting unnecessary dynamic allocations: #ifdef _WIN32 #include #else typedef char _TCHAR; #define _tmain main #endif #include #include #include #include #include // string_view // Unified way to view a string (memory and length) – without owning it // No allocation std::size_t parse(std::string_view str) { return std::count(str.begin(), str.end(), ‘e’); } int _tmain(int argc, _TCHAR *argv[]) { const std::string str = “hello world”; const char* c = “Rio de Janeiro”; std::cout 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #ifdef _WIN32 #include #else typedef char _TCHAR; #define _tmain main #endif   #include #include #include #include #include   // string_view // Unified way to view a string (memory and length) – without owning it // No allocation std::size_t parse(std::string_view str) {     return std::count(str.begin(), str.end(), ‘e’); }   int _tmain(int argc, _TCHAR *argv[]) {     const std::string str = “hello world”;     const char* c = “Rio de Janeiro”;       std::cout “Occurrences of letter ‘e’: “ parse(std::string_view(str.data(), str.length())) std::endl;     std::cout “Occurrences of letter ‘e’: “ parse(std::string_view(c, strlen(c))) std::endl;     system(“pause”);     return 0; } So, std::string_view is an extraordinary utility for great performance. But, the programmer must assure that std::string_view does not outlive the pointed-to character array. Additional functions provided by std::string_view can be found here, on the official documentation. Head over and check out the Windows string_view demo for C++Builder on GitHub.

Read More