“Foshizzle” is a modified version of the Clang compiler which supports Ebonicode++ (an alternate C++ syntax). Foshizzle supports all the existing features of Clang, but with extensions to more fully express your gansta style. All the regular C++ syntax still works, but you can now substitute Ebonicode++ keywords and operators (see below).
Here’s a sample method that calculates factorials (Note: the semicolons can be replaced with a certain expletive):
int factorialz(int n)
{
int rezult be 1;
slongas (n bepimpin 0)
{
rezult be rezult dimes n;
dissin n;
}
putou rezult;
}
I can’t take all the credit. I was inspired by the Iowa State students that first created Ebonicode (webpage no longer available).
Here are my Clang modifications: ebpp-clang30rc4.patch
Build instructions are near the end of this post.
Continue reading »
Yes, stdint.h and inttypes.h are missing from Microsoft Visual Studio. As a result, anyone who’s written cross-platform C\C++ code for Windows has probably seen this error:
error C2146: syntax error : missing ';' before identifier 'foo'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
The fact is that Visual Studio doesn’t implement C99… it implements C89 (for compatibility reasons). So, you don’t have access to familiar types like:
int8_t, int16_t, int32_t, int64_tuint8_t, uint16_t, uint32_t, uint64_tINT8_MIN,INT8_MAX, etc- The
fprintfmacrosPRId32,PRIu32, etc strtoimax(), etc
Fortunately, Alexander Chemeris has written msinttypes: an implementation of stdint.h and inttypes.h for Microsoft Visual Studio. It is licensed under the BSD license, so the headers are actually usable commercially (no viral GPL). This following quote probably goes without saying (emphasis mine):
Note though, that just adding these headers does not make Visual Studio compiler fully C99 compliant.
This project has saved me a bunch of unwanted coding. Thanks Alex!
Thomas Becker has a great article explaining C++11′s rvalue references and how they allow move semantics and perfect forwarding.
I particularly liked his summary of the 3 things you need to remember about rvalue references:
- By overloading a function like this:
void foo(X& x); // lvalue reference overload void foo(X&& x); // rvalue reference overload
you can branch at compile time on the condition “is foo being called on an lvalue or an rvalue?” The primary (and for all practical purposes, the only) application of that is to overload the copy constructor and copy assignment operator of a class for the sake of implementing move semantics. If and when you do that, make sure to pay attention to exception handling, and use the new noexcept keyword as much as you can. std::moveturns its argument into an rvalue.std::forwardallows you to achieve perfect forwarding if you use it exactly as shown:
template<typename T, typename Arg> shared_ptr<T> factory(Arg&& arg) { return shared_ptr<T>(new T(std::forward<Arg>(arg)); }
I also like his definition of lvalues and rvalues in the introduction:
The original definition of lvalues and rvalues from the earliest days of C is as follows: An lvalue is an expression
ethat may appear on the left or on the right hand side of an assignment, whereas anrvalue is an expression that can only appear on the right hand side of an assignment.In C++, this is still useful as a first, intuitive approach to lvalues and rvalues. However, C++ with its user-defined types has introduced some subtleties regarding modifiability and assignability that cause this definition to be incorrect. There is no need for us to go further into this. Here is an alternate definition which, although it can still be argued with, will put you in a position to tackle rvalue references: An lvalue is an expression that refers to a memory location and allows us to take the address of that memory location via the
&operator. An rvalue is an expression that is not an lvalue.
Cyclic Redundancy Checks are a quick and convenient way to verify if a data set has changed. They are not meant to be “secure” like a MD5 or SHA-1, but they offer a very practical solution to most problems. CRC’s are also useful for verifying if 2 data sets are equal. Here’s a simple class I use that’s efficient. Honestly, I don’t remember what flavor of CRC32 it implements (sorry), but it has always worked for what I’ve needed. Cheers!
static const uint32_t kCrc32Table[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, Continue reading »
In this post, I outline a basic GDI video window class. GDI is inefficient for rendering video, but it’s also very convinient when writing simple tools on Windows. I find myself doing it often enough that it makes sense to do a brain-dump here. This is only an outline, but it should get you over the biggest hurdles.
Outline
- Video Window Class Definition
- Creating and Destroying the Window
- The Window Thread
- The Message Pump
- Rendering a Video Frame
Things to note:
- You will need a thread in your window class to “pump” window events.
- GDI does NOT do any color conversion, so you will need to convert each frame into the same format as the display (always RGB, usually 24 or 32 bits).
Video Window Class Definition
class VideoWindow
{
public:
...
private:
static DWORD _ThreadMain(void*);
static LRESULT WINAPI _MsgProc(HWND, UINT, WPARAM, LPARAM);
CRITICAL_SECTION _lok;
HANDLE _thread;
HWND _hWnd;
HDC _hDC;
HDC _hFrameDC;
HFONT _hFont;
int _bpp; // bit depth
volatile bool _exit;
int _x, _y, _w, _h; // Window dimensions
int _imgWidth, _imgHeight, _imgLength; // Frame dimensions
unsigned char *_imgBits;
};
Creating and Destroying the Window
void VideoWindow::Create(int x, int y, int w, int h)
{
EnterCriticalSection(&_lok);
_x = x;
_y = y;
_w = w;
_h = h;
_hWnd = 0;
_exit = false;
_thread = CreateThread( NULL, NULL, (LPTHREAD_START_ROUTINE)_ThreadMain,
this, NULL, 0 );
LeaveCriticalSection(&_lok);
// Wait for window to be created. Cheap, but it works.
while (!_hWnd) {
::Sleep(100);
}
}
Continue reading »
The C99 spec requires that math.h should define the constant float value NAN. However, NAN isn’t defined in the Visual Studio version of math.h, so you have to define it yourself (VS only implements C89). It’s pretty straight-forward for 32-bit machines… here’s my implementation with cross-platform protection:
#ifdef WIN32
#ifndef NAN
static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff};
#define NAN (*(const float *) __nan)
#endif
#endif
This code is adapted from an MSDN example.
Here’s a simple function using getaddrinfo() that will take an IP address and return the address family (AF_INET for IPv4, AF_INET6 for IPv6, etc). I works on both Linux and Windows. This function will also accept hostnames and return the address family of the first address returned. You can disable this feature (and the corresponding DNS lookup) by passing the AI_NUMERICHOST flag.
// Returns the address family of an address or hostname.
// AF_INET, AF_INET6, or -1 on error.
int getaddrfamily(const char *addr)
{
struct addrinfo hint, *info =0;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
// Uncomment this to disable DNS lookup
//hint.ai_flags = AI_NUMERICHOST;
int ret = getaddrinfo(addr, 0, &hint, &info);
if (ret)
return -1;
int result = info->ai_family;
freeaddrinfo(info);
return result;
}
See RFC 3493 for more information on the latest socket API for dealing with IPv6.
A colleague of mine found a pretty cool profiling tool for Windows called Very Sleepy. It’s simple, straight-forward, free, and it works… everything I like in a tool (this is why I like the Sysinternals stuff so much). It’s also got call-graph and 64-bit support. Definitely worth checking out.
I’ve been working lately on embedding Lua 5.1.4 into a C++ application. I’m really impressed with Lua, and most things are pretty straight-forward. However, when it comes to mapping typed enumerations into Lua, I just haven’t found an easy way to do it. For example, let’s say you want to expose a C++ function into Lua called create(), which takes an enumerated type as a parameter. In C++ this would look like:
typedef enum _TYPE {
TYPE_FOO = 0,
TYPE_BAR,
TYPE_BAZ,
TYPE_MAX
} TYPE;
bool create(const TYPE type);
To me, it makes the most sense to call create() from Lua with syntax like:
> create(type.foo)
Ideally, we’d also like the following:
- The enumeration is const, and can’t be altered from Lua code.
- The C++ implementation of
create()could validate the type passed to it is the expected type.
Unfortunately, this isn’t as straight-forward as everything else I’ve done with Lua.
Solution (i.e. cut-to-the-chase and explain later)
Okay, I’m a practical guy… download lua_typed_enums.h and include it in your code. Then you can add the enums shown above to Lua by calling add_enum_to_lua():
add_enum_to_lua( L, "type",
"foo", TYPE_FOO,
"bar", TYPE_BAR,
"baz", TYPE_BAZ,
0 );
Your enums are now available in Lua as:
type.foo
type.bar
type.baz
Now, your C++ code that takes TYPE as an input and returns a boolean would be written as follows:
static int lua_create( lua_State *L )
{
if( !check_enum_type( L, "type", -1 ) ) {
/* error */
}
int value = get_enum_value( L, -1 );
/* do something cool */
lua_pushboolean( L, 1 );
return (1);
}
You can now call your create() method from Lua how we wanted:
> create(type.bar)
Look at the comments in the header file if you want more info about using add_enum_to_lua(), check_enum_type(), and get_enum_value().
How it Works
There’s no direct way to map the expected behavior of C-enums into Lua (const-ness with typing). What I did was to create a read-only Lua table representing the enumerated type and then make each value in that table have a defined type.
Let’s deal with the first task: making a read-only table. This is pretty well documented on the web, but I’ve included a drawing below that would have helped me a lot in the beginning. Let’s assume we want to represent our enum as a Lua table. We could visualize it as follows:
We could still use the type.foo syntax with this table, but a user could assign a new value to the enum like:
> type.foo = 9
To prevent this, we need to deny write access to the table. The trick to doing this is to use a metatable and set the __index and __newindex values.
So how does this work? When the user reads a value from the table (i.e. by using type.foo), Lua fails to find “foo” in the table. So it looks in the metatable for the __index key. If that is set to point to a table, then it will try to lookup the value in that table. In the case above, it finds the “foo” value and returns it like normal. However, if the user attempts to assign to type.foo, Lua follows the __newindex path, which causes a function to get called that does nothing but print an error… effectively, the write is denied. Here’s what happens:
> type.foo = 9
[string "?"]:1: Attempt to modify read-only table
Okay, cool… we’ve made read-only enumerations, but what about typing. Glad you asked! We add one more layer of abstraction, of course <groaning>:
Basically, we make each value a table that includes the actual value and a type (“type” in our example above). The check_enum_type() function looks at the “type” field in the table to make sure the correct type was passed to your function. The get_enum_value() function gets the “value” field… which is equal to the actual C-enum type you’d expect. From the Lua side, you can inspect the enums like:
> print(type.foo.value)
0
> print(type.foo.type)
type
Explicitly, “type” is a read-only table with value “foo”. The value of “foo” is the table { value=0, type="type" }. I hope this explanation helps. Obviously, I’ve been geeking out on Lua a little too much lately
ThreadNinja is a Linux library my team created that tracks pthread_create() and pthread_join() calls in an application. It prints a stacktrace where each thread is created and where it is joined. Any rogue (unjoined) threads are reported when the application exits. ThreadNinja is unobtrusive: it does NOT have to be compiled into the code. This means you can use it on applications you didn’t compile.
We found it useful and thought we’d share it. It’s be no means production code… just a tool. Hack on it, expand it, change it… whatever. It’s pretty small, so it should be easy to dive right in. We’ve released it under the BSD license.
Cut To The Chase
You can checkout the source code from Google Code, or download the version 1.0 tarball directly (threadninja.tar.gz).
To build ThreadNinja, simply untar it and call make:
> tar -zxf threadninja.tar.gz
> make
Now, simply use LD_PRELOAD to run the application:
> LD_PRELOAD=/path/to/threadninja/build/libthreadninja.so.1 TheApplication
If you don’t see function names in the stacktraces that are generated, then the application needs to be compiled with debug symbols. For my test app, I had to compile with the -rdynamic option:
> g++ -Wall -rdynamic main.cpp -lpthread
This causes the global symbol table to be included in the executable, which contains all the application’s function names. For more info, look at the --export-dynamic option on the GNU linker (ld) man page.
The Story Behind ThreadNinja
My team was assigned to stabilize a large video application that runs as a Linux-based appliance. The application consisted of 100,000+ of lines to code that was a tangle of build warnings, circular references, and many creative hacks. Our particular task was to fix a persistent set of seg-faults and memory leaks.
Continue reading »







