vim for programmer

VIM “IDE” with symbol – browsing and auto – completion

Various utilities inside VIM: media player, calendar, file explorer…

I have been using VIM for most of my daily programming, and everyday, I’ve been discovering new things about VIM. We can tune VIM into a full-fledged and powerful IDE (Integrated Development Environment) that far surpasses every others! With ctags and taglist.vim, we can build tags database, which would then enable searching, browsing all symbols, variables, functions in a code – base. cscope enhances ctags even more with advanced search & browsing features. And I would need no external diff tool since we’d already have vimdiff to compare and merge code.

Working with different types of version – control system, we’d already had vcscommand.vim, which can help interfacing with svn, cvs or git! To interact with file system, I would use NERDTree or vimExplorer, a lot of tasks with fs is done even without leaving VIM! I’m not fool enough trying to do everything with VIM, but there are many other plug-ins that you would find useful: a.vim and c.vim would help you a lot in C/C++ programming, calendar.vim helps you viewing date, and keeping small notes (diary) for each day, musicbox.vim serves you with media playing inside VIM, and vimail helps send, receiving emails with just a few convenient keystrokes!

fooled by randomness

Usually on my birthday, I would receive messages like: Congratulation to the Party! Congratulation to the government! Congratulation to President Ho Chi Minh! (the day happens to be also the Man’s birthday). But last month, I received this book, a nice gift from a friend, a soft – paperback hard – copy of the famous writing: Fooled by Randomness! I’m now half – way through the book, a bit difficult for non – English – native readers, but really interesting in every details!

My major hobby is teasing people who take themselves & the quality of their knowledge too seriously & those who don’t have the courage to sometimes say: I don’t know. You may not be able to change the world but… (www . fooled by randomness . com)

As with every outstanding thinkers and thinkings, the book’s caused controversies since it was first published (2001), written by Nassim Nicholas Taleb, a skeptical scholar and at the same time, a successful trader. I’ve been for long, looking forward to these types of cognitive thoughts! It’s too soon to have some comments on the book, but for now, the debate between Einstein and Heisenberg, between determinism and un – determinism would just go on!

elektronika

Russian Elektronika clone

Nintendo Game & Watch original.

A very sweet souvenir, a sudden reminiscence that happen to recall, my first computer game. Some day in the mid-80s, I’d got a gift, a Soviet built, hand-held device. I still remember the sound, the addictive feelings came with it! The game featured a wolf, a rabbit, likely to be seen in the Nu, pogodi! cartoon series (pronounced by us – little child as nupacachi). The game’s goal is trying to catch falling eggs, if an egg missed, it breaks and a chick is born. If 4 chicks are born, you lose! I played hundreds of games on this pad, then batteries ran out but can’t find anywhere replacement back then.

Several years later, in the late-80s, these types of games became obsolete, then seen the Nintendo’s Famicom console widespread. Now I know it was a clone of Egg (a variant of Mickey Mouse), played on console manufactured by Nintendo. Although capable of building super computers, the Soviet Union was, at the time, in shortage of consumer goods, they choose to reverse engineer various Western products.

It’s very interesting to learn about separate branches of electronics and computer science in the USSR. They had distinctive type of computers, architectures, operating systems, programming languages… Some are even found nowadays quite bizarre like the trinary computers (as apposed to binary systems we’re extensively using). It should be noticed that the Russian had very successful specific-purpose models that offer superior power in narrow fields (such as ballistic computing). Areas in their separated genealogical branches of science and technology remain mysterious until today, some are covered in the book Computing in Russia, a highly-recommended reading!

Update, May, 13rd, 2009

It was kind of a very first and famous game, yet only ones at the time know about it, in the early and mid 80s. After searching a while, I found various simulators for playing the Game & Watch series, on Linux, on Windows and even on Mac. On the left is Flash version of the game, the Soviet variant named Nu, pogodi!, you can guess from Cyrillic letters above the screen. Enjoy!

ô ăn quan

Có 50 quân dân, và 2 quân quan, mỗi quan tương đương 10 dân. Người chơi có quyền chọn di chuyển theo hướng bất kỳ, những game Mancala khác chỉ được di chuyển theo một chiều nhất định.

Ăn quân ở ô kế tiếp trong lượt đi chứ không phải ở ô đối diện của đối phương. Khi đến lượt mình mà không còn quân để đi thì phải bỏ 5 quân đã ăn được vào 5 ô của mình để tiếp tục chơi. Trường hợp không có đủ 5 quân thì phải vay của đối phương và trả lại khi trò chơi kết thúc.

Trò chơi dân gian Việt Nam Ô ăn quan thuộc họ Mancala, có nguồn gốc châu Phi và có hàng chục biến thể khác nhau trên thế giới. Khi nhỏ, tôi có chơi trò này vài lần, gọi theo tên địa phương là Ô làng chứ không phải Ô ăn quan. Hôm nay thử nhìn cái game này dưới góc độ tin học xem sao! Ô ăn quan có một số luật khác với những game Mancala khác.

Những luật bên, nhất là luật thêm & mượn quân làm Ô ăn quan phức tạp hơn nhiều so với những biến thể Mancala khác. Viết một chương trình cho máy tính chơi Ô ăn quan không phải là quá dễ dàng, dùng những heuristic đơn giản (hill-climbing, min-max, hay brute-force đến một độ sâu nhất định…) không đủ bảo đảm máy tính sẽ thắng trong nhiều trường hợp.

Trên internet, tôi không tìm được game Ô ăn quan nào theo đúng luật Việt Nam. Một số là những biến thể gần giống Ô ăn quan, một số tác giả claim là đã viết Ô ăn quan nhưng không cung cấp được link download. Có vẻ như game này không dể như khi vừa mới nghĩ đến! Bạn nào có ý kiến về chiến thuật chơi game này xin được trao đổi để cùng phát triển một trò chơi hoàn chỉnh.

Bên đây là screenshot của một Java applet tôi vừa viết trong vài tiếng đồng hồ, cho phép 2 người chơi với nhau (máy tính chỉ kiểm luật, chưa phải là một chương trình cho máy tính chơi thực sự). Những hiệu ứng đồ họa: di chuyển quân, ăn quân nhìn rất giống thật, graphics được vẽ bằng Photoshop: những viên sỏi và bàn chơi được vẽ bằng phấn trên mặt sân xi-măng… gợi lại những kỷ niệm thủa nhỏ.

minesweeper

Two more hours of work and I’ve added this hexagonal tiles to my MineSweeper! Anyone interested in the game can found the tiny binary and source code (450 LOC) here. Mine sweeping with hexagons is quite a different experience! More about MineSweeper, a simple game?

On the left: Minesweeper with hexagonal tiles

virtualization

MineSweeper running in DOSBox

Click the demo page below (jpcapplet.jar – 1.8 MB in size), it would take some times to load, embedded in it is a DOS image (floppy.img) of a floppy’s size (1.4 MB). In Linux, using dd to create a blank image file, launch JPC app, mount the empty image, fdisk to give it a partition structure, format to give it a bootable FAT12 file system, copy the files over, edit autoexec.bat to have the game run at startup, and voila – there you are, the classic DOS game of MineSweeper on the web!

Beside is screen-shot of my very first programming, the classic MineSweeper, an exercise I did first year at university. After getting started with Borland C++ 3.1, I began to write numerous toys like this; small games, graphics, animation, 3D… are among the things I was very fond of. We still had not had Internet in Vietnam then, lacking of information, we’d reinvented many wheels, including a package for displaying 3D objects (in form of polygon mess), a complete GUI for DOS with window, menu, toolbar, all kinds of controls: combo, list, button… But as they say: don’t reinvent the wheel, unless you plan on learning more about wheels, the reason we did all that fun stuff.

Back to my MineSweeper, it’s tiny, about 350 LOC (Line Of Code), using BGI (Borland Graphics Interface), C/C++ and some ASM. Yesterday, just want to check the old source, but didn’t have a Windows machine at hand, I needed to run the Borland C++ 3.1 compiler on my Linux box. Wine is good for many Windows applications, but it simply won’t work with pure DOS programs. Then I found DOSBox, you start it up in form of a console, mount a directory in local file system, have BC 3.1 installed and compiles flawlessly, and MineSweeper runs well on this virtual DOS on top of Linux!

That’s some layers of virtualization, say I want more, I want to show MineSweeper on the web, but don’t want to make change to the code, or even to the compiled binary. Could it be possible? The answer is: YES! You would need JPC, a pure Java IBM-PC emulator, it runs where there is Java: x86, RISC, mobile phone… On top of it, you can run a bundle of different OS: DOS, Linux, Windows… Then comes the delicate distinction between virtualization and emulation, hardwares, softwares, all can be virtualized to some great extent. Imagine you would run some games & utilities on a virtual DOS (or Linux) running inside JPC, hosted in Firefox browser, which in turn runs on Windows (or Linux)!

JPC can only bring about 20% power of the native machine, and even a tiny game like this is overkill to it, and mouse functioning is really crappy too. But that’s suffice to demonstrate the idea, JPC could be improved I believe. More games would be added to this Web DOS console later on! Anyone still remember Tetris, Croix-Zero, Snake, Mario…? So, what’s the points for JPC? Demonstrating the fractal principles in hardware, software evolution? Too much “nostalgia” for the “good old days” – DOS games? Anything else or just reinventing the wheel? The answer may be so, but I love this idea of cultivating the past, and pop out new things for the future!

otp (one-time-pad)

OTP takes a security problem and changes it into a
distribution problem. Modern cryptography takes a
distribution problem and changes it into a security problem.

Chuỗi khoá được in trên một cuốn sổ bé xíu, để dễ cất dấu hay tiêu huỷ khi cần thiết. Mỗi lần mã hoá dùng một (hay nhiều) tờ trong cuốn sổ, những tờ đó sẽ bị huỷ sau khi dùng, do vậy mà có cái tên one-time-pad

Hình bên: một cuốn sổ OTP của KGB, được in trên giấy phim để dể cháy khi đốt

đĩa Vigenere

Tôi đến với Computer Science khá trể, nhớ lại hồi năm nhất đại học, khi lần đầu tiên học về toán tử XOR (bit-wise operator XOR), tôi đã nghĩ ngay đến phương pháp mã hoá đơn giản và hiệu quả: thông điệp cần gửi được XOR với một chuỗi ký tự ngẫu nhiên (chuỗi khoá), ở đầu nhận, người ta XOR chuỗi đã được mã hoá với chuỗi khoá lần nữa để giải mã thông điệp. Đây chính là biểu diễn máy tính của phương pháp mã hoá cổ xưa OTP (one-time-pad) được dùng từ thời đệ nhất thế chiến.

Lincolnshire Poacher (MI6 ?) 
Magnetic Fields (Deuxième Bureau?) 

OTP được các điệp viên CIA, KGB, MI6… dùng phổ biến trong hai cuộc thế chiến. Lý do thứ nhất là vì nó đơn giản: mã & giải mã chỉ cần dùng đến tính nhẩm (có thể dùng thêm bút chì và giấy), lý do thứ hai là nó rất an toàn. Tuy đã được dùng rất lâu từ trước nhưng mãi đến khoảng năm 1940, phương pháp này mới được chứng mình bằng lý thuyết về tính an toàn tuyệt đối của nó. Chứng minh được đưa ra đồng thời và độc lập bởi Claude Shannon (nhà toán học Mỹ, cha đẻ lý thuyết thông tin) và Vladimir Kotelnikov (viện sĩ khoa học Liên bang Nga, kỹ sư chế tạo rađa).

Mã & giải mã với OTP rất đơn giản, tương đương phép XOR, ta định nghĩa phép biến đổi như sau. Mã hoá = (text T(19) + khoá X(23)) mod 26 = Q(16). Giải mã = (Q(16) – khoá X(23)) mod 26 = text T(19), với 26 là kích thước bản chữ cái (phép XOR thực chất là phép cộng và modulo cho 2, với 2 là kích thước bảng chữ cái nhị phân: 0 & 1). Những người không giỏi tính nhẩm có thể dùng “thiết bị” sau (gọi là đĩa Vigenere), đĩa gồm 2 vòng giấy đặt đồng trục. Mã hoá text T với khoá X: gióng (xoay) vị trí [X] của vòng trong với vị trí [A] của vòng ngoài, tìm [T] tại vòng ngoài, ví trí tương đương [Q] tại vòng trong chính là kết quả. Giải mã là quá trình ngược lại: gióng [Q] của vòng trong với [A] của vòng ngoài, tìm [X] tại vòng trong, vị trí tương đương [T] tại vòng ngoài là văn bản gốc.

Có một cách sử dụng OTP đặc biệt gọi là chia xẻ bí mật (secret splitting), sau khi mã hoá, văn bản gốc bị huỷ thay vì khoá, sau đó khoá và văn bản mã hoá được đưa cho hai người khác nhau cất giữ. Chỉ khi hai người này cũng đồng ý nối hai “khoá” lại với nhau thì mới giải mã ra được văn bản gốc. Tương tự, có thể chia xẻ bí mật cho 3, 4,… người bằng cách sử dụng 2, 3,… khoá. Đây là cách bảo vệ các tài nguyên đặc biệt quan trọng, trách nhiệm bảo vệ đó được chia xẻ cho nhiều người, tuy nhiên lưu ý rằng nếu chỉ một phần của bí mật bị mất đi, thì bí mật đó cũng sẽ mất đi vĩnh viễn.

OTP là phương pháp mã hoá tuyệt đối an toàn nếu được sử dụng đúng cách, và là phương pháp tuyệt đối an toàn duy nhất cho đến thời điểm hiện tại. Văn bản được mã hoá với OTP không cho biết bất kỳ thông tin gì về văn bản gốc, ngoại trừ độ dài. Với một văn bản đã mã hoá cho trước, chúng ta có thể nghĩ ra các chuỗi khoá để “giải mã” nó về bất kỳ văn bản nào chúng ta muốn! Các phương pháp mã hoá mới sau này như DES (Data Encryption Standard), AES (Advanced Encryption Standard), PGP (Pretty Good Privacy), PKI (Public Key Infastructure)… tuy tiện dụng và có nhiều ưu điểm khác, nhưng về mặt lý thuyết không phải là không phá được. Nhưng trong sử dụng thực tế, có những lý do sau khiến OTP trở nên không an toàn:

  • Chuỗi khóa OTP không thực sự ngẫu nhiên (các nhân viên thư ký của KGB tạo ra OTP bằng cách gõ ngẫu nhiên lên máy đánh chữ, nhưng xu hướng gõ phím của tay người vẫn có những pattern nhất định).

  • Việc cất giữ và tiêu huỷ OTP có quá nhiều yếu tố rủi ro (đã có tình huống CIA giải được mã nhờ một cuốn sổ OTP đã bị đốt nhưng chưa cháy hết).

  • Mỗi trang OTP chỉ được dùng một lần (đã có lúc trong tình hình khẩn cấp, nhân viên KGB bất cẩn dùng một trang OTP cho nhiều lần mã hoá, dẫn đến việc CIA giải được khoảng 1% trong số những thông điệp gửi bởi KGB trong những năm 1945 ~ 1950).

Điểm yếu nhất của OTP nằm trong quá trình trao đổi khoá (key exchange), đó là một trong những lý do hình thành phương pháp public key rất tiện dụng sau này. Đến bây giờ, khi những phương tiện mã hoá và truyền thông đã quá hiện đại, người ta vẫn còn tiếp tục dùng OTP cho những kênh thông tin thuộc loại top secret (như đường dây hotline Washington DC – Moscow, liên lạc với tàu ngầm…) vì tính tuyệt đối an toàn đã được chứng minh lý thuyết của nó. Có thể kiểm chứng dấu vết của việc sử dụng OTP trong thực tế:

Các Number Station nổi tiếng bí ẩn, là những đài phát thanh không rõ nguồn gốc, phát trên băng tần sóng ngắn (shortwave) những bản tin toàn chữ số, được xem như những hoạt động tình báo của nhiều nước. Trên internet, những Numbers Relay Pages như nrp.write2me.com là hình thức mới của Number Station, cho phép mọi người gửi đi những thông điệp bí mật. Tất cả đều dưới hình thức những bộ 5 chữ số của mã hoá OTP (e.g: 41888 42037 89537 55295 14846 82981 63440…).

biệt kích, bộ binh & cảnh sát

Từ lâu tôi có một suy nghĩ, ẩn dụ vui vui về software engineering. Nay tìm được một bài viết tương tự ở đây, người ta cũng nghĩ như mình, và diễn đạt tốt hơn. Không có cách nào khác hơn là dịch lại nguyên văn bên dưới.

Có ba “lực lượng” hoàn toàn khác biệt có liên quan đến những giai đoạn hình thành và phát triển của một công ty, đó là: “biệt kích”, “bộ binh” và “cảnh sát”.

Biệt kích

Khi xâm chiếm một vùng lãnh thổ (hay thị trường), lực lượng tham chiến đầu tiên thường là các nhóm biệt kích. Như Stephen WozniakSteve Jobs của Apple, Don Estridge của IBM PC, Mitch KaporJonathan Sachs của Lotus 1-2-3… là những nhóm biệt kích. Nhảy dù vào sau lưng địch, đổ bộ bí mật lên bờ, gây ra thật nhiều thiệt hại cho đối phương, đặt đầu cầu cho những cuộc tấn công tiếp theo là công việc của biệt kích. Họ làm điều đó bằng cách tạo ra những mẫu hình sản phẩm mà ý tưởng sáng tạo của chúng xuất sắc đến nỗi những sản phẩm tương tự không có cách nào khác hơn là thua cuộc và bị đào thải.

Với hầu hết các loại sản phẩm, “biệt kích” là nhóm duy nhất có quyền sáng tạo: đẩy công nghệ tới những giới hạn mới, tìm ra những khách hàng tiềm năng, và xem quá trình phát triển như một cuộc phiêu lưu. Tuy vậy, cái họ làm ra được còn lâu mới có thể gọi là sản phẩm, chúng thường có những điểm yếu chết người mà cá tính “biệt kích” khó lòng nhận ra được.

“Biệt kích” thường chóng chán. Tôi (ND: tác giả) nhớ lại cuộc phỏng vấn đội trưởng một đội biệt kích Hoa Kỳ sau khi đổ bộ vào Panama: Chẳng có gì thần kỳ! Chúng ta vẫn còn đang ở đây! Một đôi khi nhóm biệt kích đâm chán nản ngay cả khi mẫu sản phẩm đầu tiên vẫn chưa xuất hiện, lúc đó đành phải chờ đến khi họ có hứng thú trở lại (hay là thuê một nhóm biệt kích khác). Một ví dụ: Ron Crane, trưởng nhóm “biệt kích” tại 3COM Corp, công ty sản xuất card Ethernet trước tiên, khi đang thiết kế card này, Crane phát chán và bỏ đi nghiên cứu hiệu ứng phản xạ âm thanh trên trần nhà công ty. Mọi người đành phải chờ cho đến khi Crane kết thúc việc nghiên cứu, thiết lập nên chuẩn nội thất mới cho công ty, tiếp tục với card mạng và đưa 3COM lên mức lợi nhuận 900 triệu.

BỘ BINH

Biệt kích là người tạo bước đột phá đầu tiên, tuy vậy hầu hết mọi cuộc chiến (hay thương vụ) đều là chiến tranh quy ước. Tiếp theo sau biệt kích, lực lượng bộ binh tấn công với số lượng lớn để phát triển hơn nữa những lợi thế có được ban đầu. Thử nghiệm, cải tiến, sản xuất, tiếp thị sản phẩm dựa trên nguyên mẫu ban đầu và bắt đầu thu về lợi nhuận. Nếu biệt kích sáng tạo những cách mới đề làm bị thương đối thủ, bộ binh mới thực sự là người kết liễu hoặc đẩy lùi đối phương, chiếm lĩnh trận địa và cắm cờ chiến thắng. Đôi khi, bộ binh cũng phải sửa chữa những sai lầm mà nhóm biệt kích mắc phải. Vì là một tập thể số đông, nhiều người, nhiều loại, bộ binh cần có một cơ chế quản lý, luật lệ phức tạp mà những tay biệt kích giỏi đều cảm thấy không thích hợp.

Cảnh sát

Khi các lực lượng biệt kích và bộ binh đã tiến được về Berlin (hay Baghdad), những vùng đất bị bỏ lại phía sau cũng cần được bình định, quản lý. Lúc đó cần có một đội ngũ cảnh sát: thiết lập cuộc sống dân sự, xây dựng phát triển kinh tế. Cảnh sát thường xem công việc là công việc hơn là một cuộc phiêu lưu, họ ngại thay đổi, chấp nhận phần thưởng ít hơn với những vị trí ít rủi ro hơn. IBM, AT&T… những công ty lâu đời, đa phần thuộc lực lượng thứ 3 này, nhiều khi họ còn không nhớ những thành viên “biệt kích” hay “bộ binh” đầu tiên là những ai.

Thành lập và phát triển một công ty, hay điều hành một dự án phần mềm lớn đều cần dùng đến cả 3 lực lượng này. Dùng sai người (như “biệt kích”) vào sai vị trí (như bảo trì) là một thảm họa. Làm một “biệt kích” nghe thật hấp dẫn, tuy nhiên cũng còn tùy vào tình huống, “biệt kích” cũng có thể gây hại nghiêm trọng cho chính dự án anh ta đang phục vụ.

math expression on www

I rarely need to write mathematics expressions on the web, but the last time I did, it took me some times to figure out just how to do. It’d turned out to be pretty easy, there’s a free LaTeX rendering server at yourequations.com. Excellent site! Just feed it with a LaTeX expression, it would render an image for you to put on your web page. This may be the best solution for now, while waiting for an workable HTML version that supports math.

There’s also a guide to embed this feature onto Blogger blogs (and also WordPress, and some PHP forums…) Just insert your LaTeX code between the pre (or code) tags as below and the jsTeXrender JavaScript would do the rest for you. This works fine for any browser with JavaScript support (mouse over the expressions and you would see the underlying LaTeX code). You may also need this LaTeX Reference Card for a list of LaTeX’s symbols.

Update, Otc 1st, 2010

Due to heavy traffic, yourequations.com has ceased the service. Please see this new post on how to run a LaTeX rendering server of your own!

signals and slots

C makes U hang yourself;
C++ even gives U a rope object to hang;
C# scourges U using a rope wrapper!

I rarely talk about programming unless it comes to some new idea or something fun. However, in this article, I’m going to summarize a part of experiences in my career, about important concepts that I’ve learned and used: signals and slots. First appear and remain as fundamental concepts in the Qt library (“Qt” pronounced “cute” – which is so cute as a cross-platform application framework), the concepts has been adapted and developed into some other libraries (such as boost) and are being proposed as next standards for C++ language.

Please note that we’re talking C/C++ here, although signals & slots has been brought to many other languages (Java, Python, Ruby, JavaScript, etc.) Every coin has two sides and C/C++ is no exception, it has its own advantages and disadvantages (depend on types of applications). But the thing I like about C/C++ is that its half – civilized nature made it a strong language: the balance between abstraction and comprehensiveness has always been considered as core factor.

Noone want to build general applications using Assembly, and noone want to write lengthy code just for some simple features. To adhere the doctrine, strong – abstraction concepts must be introduced to capture grammar of the language, and simple, clear syntax that would make the code concise and comprehensive.

I came to signals & slots as solution to problems I’ve met when leading the CMS project, a DVRs managing software (client & server) with complicated GUI: a few screens, each screen can have a dozen tabs, each tabs can have hundreds of controls. Events on one control can affect other controls on other tab or screen, events can be user inputs as well as various signals come from dozens of (managed) network client machines.

The overwhelmingly – complicated communications surpass every MPM (message passing method), then signals & slots appeared as a saviour solution. To be simple, signals & slots is a very efficient mean of interaction between objects within a process space. I personally think it would be the next metaphor extension added to C/C++ language. Structure of this post would be as follow:

1. Introduction to signals & slots, from raw to abstract concepts.

2. ISO C++ compliant and cross – compiler, cross – flatform problems (would discuss about delegate and how function pointer has evolved from C to C++).

3. Different implementations of signals & slots: Qt, boost, sigslot, libsigc++

1.   INTRODUCTION

Flow of code is no more than a series of function call, and to perform asynchronous function call, traditional C programming use callback. A callback is a pointer to a function, so if you want a processing function to notify you about some event, you pass a pointer to another function (the callback) to the processing function. Callbacks have two fundamental flaws: firstly, they are not type-safe, we can never be certain that the processing function will call the callback with the correct arguments. Secondly, the callback is strongly coupled to the processing function since the processing function must know which callback to call. In C, to define function pointer, you would write something like this:

float (*my_func_ptr)(int, char *);
typedef float (*MyFuncPtrType)(int, char *);
MyFuncPtrType my_func_ptr;

When move to C++, things are a bit more complicated (note the weird syntax ->* to call a member function through pointer).

float (SomeClass::*my_memfunc_ptr)(int, char *);
my_memfunc_ptr = &SomeClass::some_member_func;
SomeClass *x = new SomeClass;
(x->*my_memfunc_ptr)(6, "Another Arbitrary Parameter");

Though a very strong concept in C, function pointer add little to the language C++. The only two uses of member function pointer in C++ are:

  • Demonstrate the tricky syntax of the language.

  • Help in implementation of delegate.

Now, imagine slots as invisible communication channels, every object can register to listen to some channels by providing delegates (pointer to a member function). The delegate would be invoked when slot is “filled” with a signal. The signals and slots mechanism is type safe: signature of a signal must match signature of the receiving slot. Signals and slots are loosely coupled: a class which emits a signal neither knows nor cares which slots receive the signal. To summarize the benifits:

  • Syntactically neater: signals & slots make for very readable code: you define the signals, you define the slots, then you wire them up.

  • Inherently robust: when either end of a signal/slot connection is destroyed, the connection is automatically removed. It is therefore impossible to emit a signal and have it arrive at a class that has already been deleted. Best of all, you don’t need to write any cleanup code.

  • Easier code reuse: since the thing that has to type-agree is the signal and the slot, not the whole class interface, it is much easier to plug together disparate classes that had never initially been intended to work in that way.

2.   DELEGATE

To summarize section 1: pointer is the root of all evils. Function pointer is the physical of callback method traditionally used in C programming. When evolved to C++, the C++ standard committee failed to address how to define function pointer to a single C++ object. With common-sense knowledge, we know that it take two elements to represent the thing: first is the address of the object itself (the implicit pointer this), second is pointer to the object’s member functions. The undefined land leads to different implementations across various compilers.

Contrary to common belief, the actual physical storage of pointer differs between various compilers, and even differs between types of pointer, e.g: pointer to a single – inheritance object, an multiple – inheritance one or virtual inheritance. The table below shows how many bytes it take to store pointers on different compilers (just make use of the operator sizeof). Then to calculate the actual member function’s address, each compiler uses one kind or another of offset:

struct BorlandMFP
{
        CODEPTR m_func_address;
        int delta, vindex;
};
if (vindex==0) adjustedthis = this + delta;
else adjustedthis = *(this + vindex –1) + delta;
C++
compiler
void*
pointer
function
pointer
single
inheritance
multiple
inheritance
virtual
inheritance
MS VC++ 4 4 4 8 12
GNU G++ 4 4 8 8 8
Borland C++ 4 4 12 12 12

So, delegate is just the new name for pointer to (an object’s) member function. The hard part really is that: since each compiler stores different type of pointers differently, there’s need for a way to store delegate in a universal manner: cross compilers and cross flatforms. Various techniques have been proposed by excellent programmers. Please refer to the articles below for specific techniques. I personally would prefer the method of Quynh Nguyen, an engineer at Global Cybersoft (Vietnam) Ltd.

3.   IMPLEMENTATIONS

To make those obscured concepts above clearer, I would go into some detailed implementations of signals & slots with the emphasize on the sigslot library, for this is really a compact lib: everything is contained in just one header file. Suppose you have a server that would receive some signal from network (tcp socket), then parse the received data and trigger some processing (display on GUI, store to disk…). We would define the “network signal” as follow (please note any number of parameters can be defined, we use an int and a char* here just for the example):

// the temmplate ‘signal2’ denote for
// a signal with 2 parameters

signal2<int, char*>m_netSig;

Then, at the place you want to process that event, e.g some class CDisplayForm, you would need to provide a function to process the signal:

DisplayForm::OnNetSig (int cmd, char* data)
{
  // the delegate would be invoked
  // when the signal is recieved

}

Please note that multiple objects can register to a same signal slot (and vice versa), e.g some class CRecordThread would also need to log that event to database. Then the listening objects would just register with the signal slot using a connect function:

// we pass the function pointer
// here to be called later

m_netSig.connect (this, &CDisplayForm::OnNetSig);

When the network signal arrive, e.g in some class CAsyncSocket, we would fire the signal and get it populated to all connected objects:

// emit the signal with it’s data
m_netSig.emit (NETSIG_DATA_RECEIVE, xmlStr);

Then the CDisplayForm and CRecordThread object would both receive the signal. Please note that when either end of the communication channel go out of scope, the connection is automatically removed, you don’t have to write any cleanup code. Just define the signal, the slot and wire them up! Any unrelated classes can be wired up in this type-safe manner without any pre-defined relation within them.

Speaking as an ex-hardware designer, I’d like software components to have pins around their edges, like ICs, so they can be ‘wired up’, but otherwise should be well behaved… I don’t want to know how that pin is wired internally – I just want to know that it will work when I send a signal into it.
(Sarah Thompson – sigslot library)