<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Eli Bendersky&#039;s website</title>
	<atom:link href="http://eli.thegreenplace.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://eli.thegreenplace.net</link>
	<description>Eli Bendersky&#039;s personal website</description>
	<lastBuildDate>Wed, 12 Jun 2013 02:34:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>Keeping persistent history in bash</title>
		<link>http://eli.thegreenplace.net/2013/06/11/keeping-persistent-history-in-bash/</link>
		<comments>http://eli.thegreenplace.net/2013/06/11/keeping-persistent-history-in-bash/#comments</comments>
		<pubDate>Wed, 12 Jun 2013 02:27:17 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Software & Tools]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3177</guid>
		<description><![CDATA[For someone spending most of his time in front of a Linux terminal, history is very important. But traditional bash history has a number of limitations, especially when multiple terminals are involved (I sometimes have dozens open). Also it&#8217;s not very good at preserving just the history you&#8217;re interested in across reboots. There are many [...]]]></description>
			<content:encoded><![CDATA[<p>For someone spending most of his time in front of a Linux terminal, history is very important. But traditional bash history has a number of limitations, especially when multiple terminals are involved (I sometimes have dozens open). Also it&#8217;s not very good at preserving just the history you&#8217;re interested in across reboots.</p>
<p>There are many approaches to improve the situation; here I want to discuss one I&#8217;ve been using very successfully in the past few months &#8211; a simple &quot;persistent history&quot; that keeps track of history across terminal instances, saving it into a dot-file in my home directory (<tt class="docutils literal"><span class="pre">~/.persistent_history</span></tt>). All commands, from all terminal instances, are saved there, forever. I found this tremendously useful in my work &#8211; it saves me time almost every day.</p>
<p>Why does it go into a <em>separate</em> history and not the <em>main</em> one which is accessible by all the existing history manipulation tools? Because IMHO the latter is still worthwhile to be kept separate for the simple need of bringing up recent commands in a single terminal, without mixing up commands from other terminals. While the terminal is open, I want the press &quot;Up&quot; and get the previous command, even if I&#8217;ve executed a 1000 other commands in other terminal instances in the meantime.</p>
<p>Persistent history is very easy to set up. Here&#8217;s the relevant portion of my <tt class="docutils literal"><span class="pre">~/.bashrc</span></tt>:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">log_bash_persistent_history()
{
  [[
    $(history 1) =~ ^\ *[0-9]+\ +([^\ ]+\ [^\ ]+)\ +(.*)$
  ]]
  local date_part=&quot;${BASH_REMATCH[1]}&quot;
  local command_part=&quot;${BASH_REMATCH[2]}&quot;
  if [ &quot;$command_part&quot; != &quot;$PERSISTENT_HISTORY_LAST&quot; ]
  then
    echo $date_part &quot;|&quot; &quot;$command_part&quot; &gt;&gt; ~/.persistent_history
    export PERSISTENT_HISTORY_LAST=&quot;$command_part&quot;
  fi
}

# Stuff to do on PROMPT_COMMAND
run_on_prompt_command()
{
    log_bash_persistent_history
}

PROMPT_COMMAND=&quot;run_on_prompt_command&quot;
</pre>
</div>
<p>The format of the history file created by this is:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">2013-06-09 17:48:11 | cat ~/.persistent_history
2013-06-09 17:49:17 | vi /home/eliben/.bashrc
2013-06-09 17:49:23 | ls
</pre>
</div>
<p>Note that an environment variable is used to avoid useless duplication (i.e. if I run <tt class="docutils literal">ls</tt> twenty times in a row, it will only be recorded once).</p>
<p>OK, so we have <tt class="docutils literal"><span class="pre">~/.persistent_history</span></tt>, how do we <em>use</em> it? First, I should say that it&#8217;s not used very often, which kind of connects to the point I made earlier about separating it from the much higher-use regular command history. Sometimes I just look into the file with <tt class="docutils literal">vi</tt> or <tt class="docutils literal">tail</tt>, but mostly this alias does the trick for me:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">alias phgrep=&#39;cat ~/.persistent_history|grep --color&#39;
</pre>
</div>
<p>The alias name mirrors another alias I&#8217;ve been using for ages:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">alias hgrep=&#39;history|grep --color&#39;
</pre>
</div>
<p>Another tool for managing persistent history is a trimmer. I said earlier this file keeps the history &quot;forever&quot;, which is a scary word &#8211; what if it grows too large? Well, first of all &#8211; worry not. At work my history file grew to about 2 MB after 3 months of heavy usage, and 2 MB is pretty small these days. Appending to the end of a file is very, very quick (I&#8217;m pretty sure it&#8217;s a constant-time operation) so the size doesn&#8217;t matter much. But trimming is easy:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">tail -20000 ~/.persistent_history | tee ~/.persistent_history
</pre>
</div>
<p>Trims to the last 20000 lines. This should be sufficient for at least a couple of months of history, and your workflow should not really rely on more than that <img src='http://eli.thegreenplace.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Finally, what&#8217;s the use of having a tool like this without employing it to collect some useless statistics. Here&#8217;s a histogram of the 15 most common commands I&#8217;ve used on my home machine&#8217;s terminal over the past 3 months:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">ls        : 865
vi        : 863
hg        : 741
cd        : 512
ll        : 289
pss       : 245
hst       : 200
python    : 168
make      : 167
git       : 148
time      : 94
python3   : 88
./python  : 88
hpu       : 82
cat       : 80
</pre>
</div>
<p>Some explanation: <tt class="docutils literal">hst</tt> is an alias for <tt class="docutils literal">hg st</tt>. <tt class="docutils literal">hpu</tt> is an alias for <tt class="docutils literal">hg pull <span class="pre">-u</span></tt>. <tt class="docutils literal">pss</tt> is my <a class="reference external" href="https://github.com/eliben/pss/">awesome pss tool</a>, and is the reason why you don&#8217;t see any calls to <tt class="docutils literal">grep</tt> and <tt class="docutils literal">find</tt> in the list. The proportion of Mercurial vs. git commands is likely to change in the very near future <a class="reference external" href="http://eli.thegreenplace.net/2013/06/09/switching-my-open-source-projects-from-bitbucket-to-github/">due to this</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/06/11/keeping-persistent-history-in-bash/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Switching my open-source projects from Bitbucket to Github</title>
		<link>http://eli.thegreenplace.net/2013/06/09/switching-my-open-source-projects-from-bitbucket-to-github/</link>
		<comments>http://eli.thegreenplace.net/2013/06/09/switching-my-open-source-projects-from-bitbucket-to-github/#comments</comments>
		<pubDate>Sun, 09 Jun 2013 23:49:18 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Version control]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3171</guid>
		<description><![CDATA[I&#8217;m switching my public open-source projects from Bitbucket to Github, and in the process also from Mercurial to git. But the switch has little to do with git vs. Mercurial; it&#8217;s mostly about Github winning the platform war vs. Bitbucket. I like Mercurial, and it was a natural choice when switching from SVN a few [...]]]></description>
			<content:encoded><![CDATA[<p><img alt="http://eli.thegreenplace.net/wp-content/uploads/2013/06/Octocat-300x249.jpg" class="align-center" src="http://eli.thegreenplace.net/wp-content/uploads/2013/06/Octocat-300x249.jpg" /></p>
<p>I&#8217;m switching my public open-source projects from Bitbucket to Github, and in the process also from Mercurial to git. But the switch has little to do with git vs. Mercurial; it&#8217;s mostly about Github winning the platform war vs. Bitbucket. I like Mercurial, and it was a natural choice when switching from SVN a few years back. Back then I wasn&#8217;t familiar with git, and I am quite a bit more familiar with it now, but still the actual SCM played little role in the decision.</p>
<p>Well, to be precise there&#8217;s one thing I find slightly more convenient about git. I really like its throwaway-branch mode of development. I want to be able to create quick local branches for hacking, throw some away, merge others and keep my history clean. I want to commit every single comma if I feel like it, without worrying about polluting the &quot;official&quot; history. So <tt class="docutils literal">git merge <span class="pre">--squash</span></tt> or squashing with interactive rebasing are workflows I appreciate. It&#8217;s not that these aren&#8217;t possible with Mercurial, which recently gave up a bit on the pedanticism and allows similar workflows via extensions. But it&#8217;s not the <em>natural</em> or the <em>familiar</em> way of working with Mercurial. As a proof of that, I kept receiving pull requests with dozens of useless small commits just to implement some feature, and kept asking the contributors to find a way to send me a single commit, or just leave the pull request machinery behind and send an old&#8217;n good patch file.</p>
<p>But I&#8217;m getting sidetracked. Github is just way, way more popular these days, especially for open source projects. I was very disappointed seeing many contributors say they&#8217;re reluctant to contribute because that would require creating a Bitbucket account and fork my projects there. Would I please just switch to Github? sigh&#8230; I can understand that &#8211; Github managed to give coding a nice social aspect &#8211; your Github profile is part of your online &quot;rep&quot;. You want your contributions to other projects to be seen through it, so people were feeling that having a fork on Bitbucket is like this hidden place no one will ever see and attribute to them.</p>
<p>A curious anecdote of the relative popularity is something I noticed when I started doing the switch. I had more followers on Github than on Bitbucket! Oh my, even though I had a number of moderately popular open source projects I was furiously hacking on Bitbucket, vs. a bunch of half-neglected forks and hacks on Github.</p>
<p>So here it is; not an overly coherent set of thoughts, I&#8217;ll admit, but I hope it makes sense. I don&#8217;t have anything against Mercurial or Bitbucket &#8211; I&#8217;m still a user of both. But the higher-profile open-source projects are now on Github. Happy hacking.</p>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/06/09/switching-my-open-source-projects-from-bitbucket-to-github/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How require loads modules in Node.js</title>
		<link>http://eli.thegreenplace.net/2013/05/27/how-require-loads-modules-in-node-js/</link>
		<comments>http://eli.thegreenplace.net/2013/05/27/how-require-loads-modules-in-node-js/#comments</comments>
		<pubDate>Mon, 27 May 2013 16:22:04 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3157</guid>
		<description><![CDATA[One of the useful tools Node.js adds on top of standard ECMAScript is a notation for defining and using modules. A &#34;module&#34; exports objects and functions by adding them to exports, and another module can import it by using require. The semantics are explained well in the official documentation. While the documentation does a good [...]]]></description>
			<content:encoded><![CDATA[<p>One of the useful tools Node.js adds on top of standard ECMAScript is a notation for defining and using modules. A &quot;module&quot; exports objects and functions by adding them to <tt class="docutils literal">exports</tt>, and another module can import it by using <tt class="docutils literal">require</tt>. The semantics are explained well <a class="reference external" href="http://nodejs.org/api/modules.html">in the official documentation</a>.</p>
<p>While the documentation does a good job describing how <tt class="docutils literal">require</tt> finds the module to import, it doesn&#8217;t say much about how the importing itself happens, and how the <tt class="docutils literal">exports</tt> and <tt class="docutils literal">module</tt> objects are magically visible and usable in the module&#8217;s code. Here I want to provide a lower-level view of this missing link, gleaned from the source code of Node.js v0.10.8 (<tt class="docutils literal">lib/module.js</tt>).</p>
<p>As the documentation linked above explains, there are a few places modules can be found in by <tt class="docutils literal">require</tt>. There&#8217;s also a number of different imports <tt class="docutils literal">require</tt> can perform &#8211; from folders, from JSON files, from compiled Node modules (C++), and so on. Here I&#8217;ll focus on importing from a regular JavaScript source file (<tt class="docutils literal">.js</tt>).</p>
<p>Code from <tt class="docutils literal">.js</tt> files is simply read into a string. Next, the code string is wrapped with a function:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">(<span style="color: #00007f; font-weight: bold">function</span> (exports, require, module, __filename, __dirname) {
   <span style="color: #007f00">// &lt;-- MODULE CONTENTS HERE --&gt;</span>
});
</pre>
</div>
<p>These wrapped contents are evaluated by the JavaScript VM, and the result is a function object; let&#8217;s call it <tt class="docutils literal">module_func</tt>. This function is invoked as follows:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">module_func.apply(module.exports,
                  [module.exports, require, module, filename, dirname]);
</pre>
</div>
<p>And the return value of <tt class="docutils literal">require</tt> is then <tt class="docutils literal">module.exports</tt>.</p>
<p>What&#8217;s <tt class="docutils literal">module</tt>? It&#8217;s the special module object the <tt class="docutils literal">require</tt> mechanism has built for loading our module. It&#8217;s actually described quite well in the modules documentation I mentioned before. That page says:</p>
<blockquote><p>
In each module, the <tt class="docutils literal">module</tt> free variable is a reference to the object representing the current module. In particular <tt class="docutils literal">module.exports</tt> is accessible via the <tt class="docutils literal">exports</tt> module-global. <tt class="docutils literal">module</tt> isn&#8217;t actually a global but rather local to each module.</p></blockquote>
<p>Now it should be obvious how this comes to be. The wrapper function created for our code has the arguments <tt class="docutils literal">module</tt> and <tt class="docutils literal">exports</tt>, which become visible in the code. The <tt class="docutils literal">apply</tt> invocation above shows what they get bound to. What it also does is set <tt class="docutils literal">this</tt> in the global scope of our code to the <tt class="docutils literal">exports</tt> property of the module. So the following are all equivalent ways to add stuff to a module&#8217;s exports:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">exports.say_hi = <span style="color: #00007f; font-weight: bold">function</span> () {console.log(<span style="color: #7f007f">&#39;hi&#39;</span>);}
module.exports.say_bye = <span style="color: #00007f; font-weight: bold">function</span> () {console.log(<span style="color: #7f007f">&#39;bye&#39;</span>);}
<span style="color: #00007f; font-weight: bold">this</span>.say_farewell = <span style="color: #00007f; font-weight: bold">function</span> () {console.log(<span style="color: #7f007f">&#39;farewell&#39;</span>);}
</pre>
</div>
<p>The last way look suspicious. We know that by default, variables in the code don&#8217;t get exported. In other words, in:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #00007f; font-weight: bold">var</span> foo = <span style="color: #007f7f">1</span>;
exports.bar = <span style="color: #007f7f">2</span>;
</pre>
</div>
<p>While <tt class="docutils literal">bar</tt> is exported to <tt class="docutils literal">require</tt>, <tt class="docutils literal">foo</tt> is not. But how can this be, if <tt class="docutils literal">this</tt> is bound to <tt class="docutils literal">exports</tt>? Doesn&#8217;t <tt class="docutils literal">var foo = 1</tt> add <tt class="docutils literal">foo</tt> to <tt class="docutils literal">this</tt>, being the global object?</p>
<p>This is only puzzling if you think of your code as stand-alone JavaScript, in which the global scope is truly global. But recall, from a few paragraphs above, that our code is wrapped in a function. So the &quot;global&quot; scope in the module is actually function scope. In function scope, variables don&#8217;t get auto-bound to <tt class="docutils literal">this</tt>. Mystery solved.</p>
<p>One final note: Node.js has a few useful flags you can set as environment variables for debugging. In particular, I&#8217;ve found setting:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%">$ NODE_DEBUG=module node &lt;file.js&gt;
</pre>
</div>
<p>Very handy for following through the module loading process <tt class="docutils literal">require</tt> does.</p>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/05/27/how-require-loads-modules-in-node-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python will have enums in 3.4!</title>
		<link>http://eli.thegreenplace.net/2013/05/10/python-will-have-enums-in-3-4/</link>
		<comments>http://eli.thegreenplace.net/2013/05/10/python-will-have-enums-in-3-4/#comments</comments>
		<pubDate>Fri, 10 May 2013 13:06:05 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3148</guid>
		<description><![CDATA[After months of intensive discussion (more than a 1000 emails in dozens of threads spread over two mailing lists, and a couple of hundred additional private emails), PEP 435 has been accepted and Python will finally have an enumeration type in 3.4! The discussion and decision process has been long and arduous, but eventually very [...]]]></description>
			<content:encoded><![CDATA[<p>After months of intensive discussion (more than a 1000 emails in dozens of threads spread over two mailing lists, and a couple of hundred additional private emails), <a href="http://www.python.org/dev/peps/pep-0435/">PEP 435</a> has been <a href="http://mail.python.org/pipermail/python-dev/2013-May/126112.html">accepted</a> and Python will finally have an enumeration type in 3.4!</p>
<p>The discussion and decision process has been long and arduous, but eventually very positive. A collective brain is certainly better than any single one; the final proposal is better in a number of ways than the initial one, and the vast majority of Python core developers now feel good about it (give or take a couple of very minor issues).</p>
<p>I&#8217;ve been told enums have been debated on Python development lists for years. There&#8217;s at least one earlier PEP (354) that&#8217;s been discussed and rejected in 2005.</p>
<p>I think part of the success of the current attempt can be attributed to the advances in metaclasses that has been made in the past few releases (3.x). These advances allow very nice syntax of enum definitions that provides a lot of convenient features for free. I tried to find <a href="http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/">interesting examples of metaclasses in the standard library</a> in 2011; Once the enum gets pushed I&#8217;ll have a much better example <img src='http://eli.thegreenplace.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/05/10/python-will-have-enums-in-3-4/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Ten years of blogging</title>
		<link>http://eli.thegreenplace.net/2013/05/06/ten-years-of-blogging/</link>
		<comments>http://eli.thegreenplace.net/2013/05/06/ten-years-of-blogging/#comments</comments>
		<pubDate>Mon, 06 May 2013 12:32:03 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Blogging]]></category>
		<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3144</guid>
		<description><![CDATA[It has occurred to me that the first post in this blog was 10 years ago, so I decided to dig up a bit of history. 10 years is a long time! As the post linked above shows, I even called it &#34;weblog&#34; then. The term &#34;blog&#34; seems to have been coined in 1999, but [...]]]></description>
			<content:encoded><![CDATA[<p>It has occurred to me that the first post in this blog was <a class="reference external" href="http://eli.thegreenplace.net/2003/05/06/why-start-a-weblog/">10 years ago</a>, so I decided to dig up a bit of history. 10 years is a long time! As the post linked above shows, I even called it &quot;weblog&quot; then. The term &quot;blog&quot; seems to have been coined in 1999, but probably wasn&#8217;t popular enough in 2003 yet. That post also closes with a hope that the blog will last; it sure did.</p>
<p>In these 10 years the blog went from an obscure journal on <a class="reference external" href="http://use.perl.org/">use.perl.org</a> that only a few people knew about to 66,000 unique visitors with half a million page views a month on average (stats for end-of 2012).</p>
<p>While it looks very different from the initial &quot;weblog&quot;, it actually went through relatively few incarnations for its age. Starting <a class="reference external" href="http://eli.thegreenplace.net/2005/09/02/becoming-unhappy-with-useperlorg/">somewhere in 2005</a> I became unhappy with use.perl.org and eventually <a class="reference external" href="http://eli.thegreenplace.net/2006/03/28/my-transition-to-blogger-is-complete/">moved the blog to Blogger</a>. But Blogger itself was quite limited for serious programming-related blogging at the time, so it took me only two weeks to figure out it&#8217;s not quite what I wanted and <a class="reference external" href="http://eli.thegreenplace.net/2006/04/12/migrating-to-wordpress/">move to a WordPress-based blog</a> on my own domain and shared hosting (Bluehost). In the seven years that has passed since, the blog changed very little visually. I stretched the main viewing area bit by bit as high-resolution monitors became more common, installed a couple of minor plugins, but that&#8217;s it.</p>
<p>What did change was the quality of content. As I <a class="reference external" href="http://eli.thegreenplace.net/2013/01/06/this-blog-and-google-division-of-responsibilities/">wrote here</a>, the blog became much more technical with time, leaving the shorter and more personal posts to outlets like G+. The amount of technical content is also the reason the blog&#8217;s popularity grew rapidly in the past few years. Apparently more people want to know how debuggers work and about the internals of Python and Linux loaders than about some random cool library I found or how I spent the last week at work being bored. Go figure.</p>
<p>So what&#8217;s next?</p>
<p>Dedicated readers will notice that the amount of in-depth posts has slowed down in the past few months. This was to be expected, having moved to a different continent and started a much more demanding job. But I still hope to continue posting articles from time to time. This blog is far from being done! As for infrastructure, I was actually pondering to make a large change after yet another <a class="reference external" href="http://eli.thegreenplace.net/2012/10/14/thinking-of-dumping-wordpress/">break-your-site WordPress upgrade</a>. But I still haven&#8217;t found time to do this. Maybe at some point I will.</p>
<p>So thanks for reading, and wishing myself at least another 10 years of blogging. It has been an incredibly positive experience for me in many respects, and I have full intention of keeping it up as long as I can.</p>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/05/06/ten-years-of-blogging/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Bootstrapping virtualenv</title>
		<link>http://eli.thegreenplace.net/2013/04/20/bootstrapping-virtualenv/</link>
		<comments>http://eli.thegreenplace.net/2013/04/20/bootstrapping-virtualenv/#comments</comments>
		<pubDate>Sat, 20 Apr 2013 12:18:37 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3138</guid>
		<description><![CDATA[The packaging situation in Python is &#34;imperfect&#34; for a good reason &#8211; packaging is simply a very difficult problem to solve (see the amount of effort poured into Linux distribution package management for reference). One of the core issues is that project X may require version V of library L, and when you come to [...]]]></description>
			<content:encoded><![CDATA[<p>The packaging situation in Python is &quot;imperfect&quot; for a good reason &#8211; packaging is simply a very difficult problem to solve (see the amount of effort poured into Linux distribution package management for reference). One of the core issues is that project X may require version V of library L, and when you come to install project Y it may refuse to work with that version and require a newer one, with which project X can&#8217;t work. So you&#8217;re in an impasse.</p>
<p>The solution many Python programmers and projects have adopted is to use <a class="reference external" href="http://www.virtualenv.org">virtualenv</a>. If you haven&#8217;t heard about virtualenv, you&#8217;re missing out &#8211; go read about it now.</p>
<p>I&#8217;m not going to write a tutorial about virtualenv or extoll its virtues here &#8211; enough bits have been spilled about this on the net already. What I plan to do is share an interesting problem I ran into and the solution I settled on.</p>
<p>I had to install some packages (Sphinx and related tools) on a new machine into a virtualenv. But the machine only had a basic Python installation, without setuptools or distribute, and without virtualenv. These aren&#8217;t hard to install, but I wondered if there&#8217;s an easy way to avoid installing anything. Turns out there is.</p>
<p>The idea is to create a &quot;bootstrap&quot; virtual environment that would have all the required tools to create additional virtual environments. It turns out to be quite easy with the following script (inspired by the answer in <a class="reference external" href="http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python">this SO discussion</a>):</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #00007f; font-weight: bold">import</span> <span style="color: #00007f">sys</span>
<span style="color: #00007f; font-weight: bold">import</span> <span style="color: #00007f">subprocess</span>

VENV_VERSION = <span style="color: #7f007f">&#39;1.9.1&#39;</span>
PYPI_VENV_BASE = <span style="color: #7f007f">&#39;http://pypi.python.org/packages/source/v/virtualenv&#39;</span>
PYTHON = <span style="color: #7f007f">&#39;python2&#39;</span>
INITIAL_ENV = <span style="color: #7f007f">&#39;py-env0&#39;</span>

<span style="color: #00007f; font-weight: bold">def</span> <span style="color: #00007f">shellcmd</span>(cmd, echo=<span style="color: #00007f">True</span>):
    <span style="color: #7f007f">&quot;&quot;&quot; Run &#39;cmd&#39; in the shell and return its standard out.</span>
<span style="color: #7f007f">    &quot;&quot;&quot;</span>
    <span style="color: #00007f; font-weight: bold">if</span> echo: <span style="color: #00007f; font-weight: bold">print</span> <span style="color: #7f007f">&#39;[cmd] {0}&#39;</span>.format(cmd)
    out = subprocess.check_output(cmd, stderr=sys.stderr, shell=<span style="color: #00007f">True</span>)
    <span style="color: #00007f; font-weight: bold">if</span> echo: <span style="color: #00007f; font-weight: bold">print</span> out
    <span style="color: #00007f; font-weight: bold">return</span> out

dirname = <span style="color: #7f007f">&#39;virtualenv-&#39;</span> + VENV_VERSION
tgz_file = dirname + <span style="color: #7f007f">&#39;.tar.gz&#39;</span>

<span style="color: #007f00"># Fetch virtualenv from PyPI</span>
venv_url = PYPI_VENV_BASE + <span style="color: #7f007f">&#39;/&#39;</span> + tgz_file
shellcmd(<span style="color: #7f007f">&#39;curl -O {0}&#39;</span>.format(venv_url))

<span style="color: #007f00"># Untar</span>
shellcmd(<span style="color: #7f007f">&#39;tar xzf {0}&#39;</span>.format(tgz_file))

<span style="color: #007f00"># Create the initial env</span>
shellcmd(<span style="color: #7f007f">&#39;{0} {1}/virtualenv.py {2}&#39;</span>.format(PYTHON, dirname, INITIAL_ENV))

<span style="color: #007f00"># Install the virtualenv package itself into the initial env</span>
shellcmd(<span style="color: #7f007f">&#39;{0}/bin/pip install {1}&#39;</span>.format(INITIAL_ENV, tgz_file))

<span style="color: #007f00"># Cleanup</span>
shellcmd(<span style="color: #7f007f">&#39;rm -rf {0} {1}&#39;</span>.format(dirname, tgz_file))
</pre>
</div>
<p>The script downloads and unpacks a recent virtualenv (substitute your desired version in <tt class="docutils literal">VENV_VERSION</tt>) from PyPI and uses it directly (without installing) to create a new virtual env. By default, virtualenv will install setuptools and <tt class="docutils literal">pip</tt> into this environment. Then, the script also installs virtualenv into the same environment. This is the bootstrap part.</p>
<p>Voila! <tt class="docutils literal"><span class="pre">py-env0</span></tt> (or whatever you substituted in <tt class="docutils literal">INITIAL_ENV</tt>) is now a self-contained virtual environment with all the tools you need to create new environments and install stuff into them.</p>
<p>This script is for Python 2 but can be trivially adapted for Python 3. In Python 3, the situation is actually more interesting. Python 3.3 (which is really the one you ought to be using if you&#8217;ve switched to 3 already) comes with virtualenv in the standard library (<tt class="docutils literal">venv</tt> package), so downloading and installing it is not required.</p>
<p>That said, its virtualenv will not install setuptools and <tt class="docutils literal">pip</tt> into the environments it creates. So YMMV here: if you need setuptools and pip there, go with a variation of the script above. If not, you don&#8217;t need anything special really, just use the <tt class="docutils literal">python3.3 <span class="pre">-m</span> venv</tt>.</p>
<p>P.S. The packaging situation <em>is</em> getting better though. There was a lot of focus during the recent PyCon on this. One of the interesting announcements was that distribute is merging back into setuptools.</p>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/04/20/bootstrapping-virtualenv/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Summary of reading:  January &#8211; March 2013</title>
		<link>http://eli.thegreenplace.net/2013/04/03/summary-of-reading-january-march-2013/</link>
		<comments>http://eli.thegreenplace.net/2013/04/03/summary-of-reading-january-march-2013/#comments</comments>
		<pubDate>Thu, 04 Apr 2013 03:07:14 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Book reviews]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3130</guid>
		<description><![CDATA[&#34;The spy who came from the cold&#34; by John le Carre &#8211; I found this book completely by chance by browsing for something unrelated. With acclaims to be &#34;the best spy novel of all times&#34;, it looked like something I should give a chance. Well, I didn&#8217;t read that many spy novels so I don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<ul class="simple">
<li>&quot;The spy who came from the cold&quot; by John le Carre &#8211; I found this book completely by chance by browsing for something unrelated. With acclaims to be &quot;the best spy novel of all times&quot;, it looked like something I should give a chance. Well, I didn&#8217;t read that many spy novels so I don&#8217;t really have good points for comparison, but this book is very good. The first 3/4ths are excellent, even. Alas, the ending was not entirely to my taste. I think the author could have done better. Overall though, highly recommended.</li>
<li>&quot;Shawshank Redemption&quot; by Stephen King &#8211; technically a re-read since this is the second time I read this book. But the first time was before the blog was established. I really like this book &#8211; it&#8217;s short and very well written. And yet, it&#8217;s better than the movie (although the movie is also great).</li>
<li>&quot;Debt: The first 5000 years&quot; by David Graeber &#8211; some books are so well reviewed that I feel bad for not liking them. But what can you do&#8230; This book was almost unreadable for me. The author made an insightful claim in the beginning (debt originated long before money) and then went on an on to examine all of human history from his point of view, linking everything to debt. But you can really link <em>everything</em> to debt if you try hard enough (try harder and you can link everything to broccoli). Hence I found the book lacked a meaningful theme, and isn&#8217;t written in a particularly interesting way. Perhaps it appears more exciting to people with interest in certain domains of economics.</li>
<li>&quot;Steve Jobs&quot; by Walter Isaacson (read in Hebrew) &#8211; The official biography of Steve Jobs. Decent book, very readable for a biography. Some of the technical details appear to be less accurate than one would hope for, but this isn&#8217;t a big deal overall. Unfortunately what I had in hands was the Hebrew translation which was as awful as usual, but overall once I learned to ignore the crap the book was enjoyable.</li>
<li>&quot;Memories after my death&quot; by Yair Lapid (read in Hebrew) &#8211; a biography of the author&#8217;s father, <a class="reference external" href="http://en.wikipedia.org/wiki/Yosef_Lapid">Yosef (Tommy) Lapid</a>. Written in an unusual (for a biography) first-person manner, this book turned out to be much better than I initially expected. I was fond of Lapid while he was active, but it turns out that I didn&#8217;t know even 1/10th of what he achieved in his life. Most of all, I was not aware of his ruthlessly objective and moral character that&#8217;s certainly worthy of serving as a role model. Couple that with very good writing, and this makes for an excellent book.</li>
<li>&quot;Tmux &#8211; Productive mouse-free development&quot; by Brian P. Hogan &#8211; an excellent short guide to the tmux program. When getting set up, you can skim the important parts of this book in less than an hour, and keep it as a handy reference afterwards. I like it that the book is written by an actual programmer who &quot;gets&quot; the way other programmers want their configuration to be done.</li>
</ul>
<p>Re-reads:</p>
<ul class="simple">
<li>&quot;A pale blue dot&quot; by Carl Sagan</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/04/03/summary-of-reading-january-march-2013/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>pss v1.37 release &#8211; testing help wanted</title>
		<link>http://eli.thegreenplace.net/2013/03/21/pss-v1-37-release-testing-help-wanted/</link>
		<comments>http://eli.thegreenplace.net/2013/03/21/pss-v1-37-release-testing-help-wanted/#comments</comments>
		<pubDate>Thu, 21 Mar 2013 12:59:07 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Software & Tools]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3121</guid>
		<description><![CDATA[Update 23.03.2013: version 1.38 was released with an important bug-fix. If you&#8217;ve installed 1.37, please upgrade. If not, still please upgrade Since pss was first released a year and a half ago, it has become an indispensable tool in my, and many other developers&#8217; toolbox. pss has matured and underwent multiple feature and bug-fix releases. [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update 23.03.2013: version 1.38 was released with an important bug-fix. If you&#8217;ve installed 1.37, please upgrade. If not, still please upgrade <img src='http://eli.thegreenplace.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </strong></p>
<p>Since <strong>pss</strong> was <a href="http://eli.thegreenplace.net/2011/10/14/announcing-pss-a-tool-for-searching-inside-source-code/">first released a year and a half ago</a>, it has become an indispensable tool in my, and many other developers&#8217; toolbox.</p>
<p><strong>pss</strong> has matured and underwent multiple feature and bug-fix releases. Today I made a <a href="https://pypi.python.org/pypi/pss">new release</a> with a slightly larger amount of changes than usual (as well as some nice optimizations that make <strong>pss</strong> run faster) and figured it&#8217;s time to move the major version dial from 0, signaling that I consider <strong>pss</strong> to be a mature and stable project. Here&#8217;s the list of changes:</p>
<pre>
+ Version 1.37 (21.03.2013)

  - Fixed the output of --help-types to describe file patterns more faithfully.
  - Issue #35: Fix the -w option to work properly on Python 3
  - Added '.tox' to the set of directories ignored by default.
  - Issue #34: Support for --cython
  - Added support for the .el extension for Emacs Lisp
  - Issue #36: Fixed the --match option.
  - Issue #37: Allow comma-separated lists in --ignore-dirs
  - Optimize the files-with-matches option by looking for a single match within
    a file instead of all matches.
  - Issue #38: Optimize matching of non-regex patterns, which is very common.
    Measured speedup of 10-20%.
</pre>
<p>While one of the original goals of pss was to work well on Windows without having to install additional packages, I&#8217;m now in a situation where I don&#8217;t have easy access to any Windows machine. I&#8217;m 99% sure pss keeps working on Windows but haven&#8217;t tested it. Therefore, if you&#8217;re using pss on Windows &#8211; please download the <a href="https://pypi.python.org/pypi/pss">new release from PyPI</a> and let me know if you run into any problems. Thanks in advance.</p>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/03/21/pss-v1-37-release-testing-help-wanted/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Python FFI with ctypes and cffi</title>
		<link>http://eli.thegreenplace.net/2013/03/09/python-ffi-with-ctypes-and-cffi/</link>
		<comments>http://eli.thegreenplace.net/2013/03/09/python-ffi-with-ctypes-and-cffi/#comments</comments>
		<pubDate>Sat, 09 Mar 2013 13:41:05 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3113</guid>
		<description><![CDATA[In a previous post, I demonstrated how to use libffi to perform fully dynamic calls to C code, where &#34;fully dynamic&#34; means that even the types of the arguments and return values are determined at runtime. Here I want to discuss how the same task is done from Python, both with the existing stdlib ctypes [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a class="reference external" href="http://eli.thegreenplace.net/2013/03/04/flexible-runtime-interface-to-shared-libraries-with-libffi/">previous post</a>, I demonstrated how to use <tt class="docutils literal">libffi</tt> to perform fully dynamic calls to C code, where &quot;fully dynamic&quot; means that even the types of the arguments and return values are determined at runtime.</p>
<p>Here I want to discuss how the same task is done from Python, both with the existing stdlib <tt class="docutils literal">ctypes</tt> package and the new <a class="reference external" href="https://bitbucket.org/cffi/cffi">cffi</a> library, developed by the PyPy team and a candidate for inclusion into the Python stdlib in the future.</p>
<div class="section" id="with-ctypes">
<h3>With ctypes</h3>
<p>I&#8217;ll start with the shared object discussed before; the following code loads and runs it in Python using <tt class="docutils literal">ctypes</tt>. I tested it on Python 3.2, but other versions should work too (including 2.7):</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #00007f; font-weight: bold">from</span> <span style="color: #00007f">ctypes</span> <span style="color: #00007f; font-weight: bold">import</span> cdll, Structure, c_int, c_double, c_uint

lib = cdll.LoadLibrary(<span style="color: #7f007f">&#39;./libsomelib.so&#39;</span>)
<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Loaded lib {0}&#39;</span>.format(lib))

<span style="color: #007f00"># Describe the DataPoint structure to ctypes.</span>
<span style="color: #00007f; font-weight: bold">class</span> <span style="color: #00007f">DataPoint</span>(Structure):
    _fields_ = [(<span style="color: #7f007f">&#39;num&#39;</span>, c_int),
                (<span style="color: #7f007f">&#39;dnum&#39;</span>, c_double)]

<span style="color: #007f00"># Initialize the DataPoint[4] argument. Since we just use the DataPoint[4]</span>
<span style="color: #007f00"># type once, an anonymous instance will do.</span>
dps = (DataPoint * <span style="color: #007f7f">4</span>)((<span style="color: #007f7f">2</span>, <span style="color: #007f7f">2.2</span>), (<span style="color: #007f7f">3</span>, <span style="color: #007f7f">3.3</span>), (<span style="color: #007f7f">4</span>, <span style="color: #007f7f">4.4</span>), (<span style="color: #007f7f">5</span>, <span style="color: #007f7f">5.5</span>))

<span style="color: #007f00"># Grab add_data from the library and specify its return type.</span>
<span style="color: #007f00"># Note: .argtypes can also be specified</span>
add_data_fn = lib.add_data
add_data_fn.restype = DataPoint

<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Calling add_data via ctypes&#39;</span>)
dout = add_data_fn(dps, <span style="color: #007f7f">4</span>)
<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;dout = {0}, {1}&#39;</span>.format(dout.num, dout.dnum))
</pre>
</div>
<p>This is pretty straightforward. As far as dynamic language FFIs go, <tt class="docutils literal">ctypes</tt> is pretty good. But we can do better. The main problem with <tt class="docutils literal">ctypes</tt> is that we have to fully repeat the C declarations to <tt class="docutils literal">ctypes</tt>, using its specific API. For example, see the description of the <tt class="docutils literal">DataPoint</tt> structure. The return type should also be explicitly specified. Not only is this a lot of work for wrapping non-trivial C libraries, it&#8217;s also error prone. If you make a mistake translating a C header to a <tt class="docutils literal">ctypes</tt> description, you will likely get a segfault at runtime which isn&#8217;t easy to debug without having a debug build of Python available. <tt class="docutils literal">ctypes</tt> allows us to explicitly specify <tt class="docutils literal">argtypes</tt> on a function for some measure of type checking, but this is only within the Python code &#8211; given that you got the declaration right, it will help with passing the correct types of objects. But if you didn&#8217;t get the declaration right, nothing will save you.</p>
</div>
<div class="section" id="how-does-it-work">
<h3>How does it work?</h3>
<p><tt class="docutils literal">ctypes</tt> is a Python wrapper around <tt class="docutils literal">libffi</tt>. The CPython project carries a version of <tt class="docutils literal">libffi</tt> with it, and <tt class="docutils literal">ctypes</tt> consists of a C extension module linking to <tt class="docutils literal">libffi</tt> and Python code for the required glue. If you understand how to use <tt class="docutils literal">libffi</tt>, it should be easy to see how <tt class="docutils literal">ctypes</tt> works.</p>
<p>While <tt class="docutils literal">libffi</tt> is quite powerful, it also has some limitations, which by extension apply to <tt class="docutils literal">ctypes</tt>. For example, passing unions by value to dynamically-loaded functions <a class="reference external" href="http://bugs.python.org/issue16575">is not supported</a>. But overall, the benefits outweigh the limitations, which are not hard to work around when needed.</p>
</div>
<div class="section" id="with-cffi">
<h3>With cffi</h3>
<p><tt class="docutils literal">cffi</tt> tries to improve on <tt class="docutils literal">ctypes</tt> by using an interesting approach. It allows you to avoid re-writing your C declarations in <tt class="docutils literal">ctypes</tt> notation, by being able to parse actual C declarations and inferring the required data types and function signatures automatically. Here&#8217;s the same example implemented with <tt class="docutils literal">cffi</tt> (tested with <tt class="docutils literal">cffi</tt> 0.5 on Python 3.2):</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #00007f; font-weight: bold">from</span> <span style="color: #00007f">cffi</span> <span style="color: #00007f; font-weight: bold">import</span> FFI

ffi = FFI()

lib = ffi.dlopen(<span style="color: #7f007f">&#39;./libsomelib.so&#39;</span>)
<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Loaded lib {0}&#39;</span>.format(lib))

<span style="color: #007f00"># Describe the data type and function prototype to cffi.</span>
ffi.cdef(<span style="color: #7f007f">&#39;&#39;&#39;</span>
<span style="color: #7f007f">typedef struct {</span>
<span style="color: #7f007f">    int num;</span>
<span style="color: #7f007f">    double dnum;</span>
<span style="color: #7f007f">} DataPoint;</span>

<span style="color: #7f007f">DataPoint add_data(const DataPoint* dps, unsigned n);</span>
<span style="color: #7f007f">&#39;&#39;&#39;</span>)

<span style="color: #007f00"># Create an array of DataPoint structs and initialize it.</span>
dps = ffi.new(<span style="color: #7f007f">&#39;DataPoint[]&#39;</span>, [(<span style="color: #007f7f">2</span>, <span style="color: #007f7f">2.2</span>), (<span style="color: #007f7f">3</span>, <span style="color: #007f7f">3.3</span>), (<span style="color: #007f7f">4</span>, <span style="color: #007f7f">4.4</span>), (<span style="color: #007f7f">5</span>, <span style="color: #007f7f">5.5</span>)])

<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Calling add_data via cffi&#39;</span>)
<span style="color: #007f00"># Interesting variation: passing invalid arguments to add_data will trigger</span>
<span style="color: #007f00"># a cffi type-checking exception.</span>
dout = lib.add_data(dps, <span style="color: #007f7f">4</span>)
<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;dout = {0}, {1}&#39;</span>.format(dout.num, dout.dnum))
</pre>
</div>
<p>Instead of tediously describing the C declarations to Python, <tt class="docutils literal">cffi</tt> just consumes them directly and produces all the required glue automatically. It&#8217;s much harder to get things wrong and run into segfaults.</p>
<p>Note that this demonstrates what <tt class="docutils literal">cffi</tt> calls <em>the ABI level</em>. There&#8217;s another, more ambitious, use of <tt class="docutils literal">cffi</tt> which uses the system C compiler to auto-complete missing parts of declarations. I&#8217;m just focusing on the ABI level here, since it requires no C compiler. How does it work? Deep down, <tt class="docutils literal">cffi</tt> also relies on <tt class="docutils literal">libffi</tt> to generate the actual low-level calls. To parse the C declarations, it uses <a class="reference external" href="https://bitbucket.org/eliben/pycparser">pycparser</a>.</p>
<p>Another cool thing about <tt class="docutils literal">cffi</tt> is that being part of the PyPy ecosystem, it can actually benefit from PyPy&#8217;s JIT capabilities. As I&#8217;ve mentioned in a previous post, using <tt class="docutils literal">libffi</tt> is much slower than compiler-generated calls because a lot of the argument set-up work has to happen for each call. But once we actually start running, in practice the signatures of called functions never change. So a JIT compiler could be smarter about it and generate faster, more direct calls. I don&#8217;t know whether PyPy is already doing this with <tt class="docutils literal">cffi</tt>, but I&#8217;m pretty sure it&#8217;s in their plans.</p>
</div>
<div class="section" id="a-more-complex-example">
<h3>A more complex example</h3>
<p>I want to show another example, which demonstrates a more involved function being called &#8211; the POSIX <tt class="docutils literal">readdir_r</tt> (the reentrant version of <tt class="docutils literal">readdir</tt>). This example is based on some <tt class="docutils literal">demo/</tt> code in the <tt class="docutils literal">cffi</tt> source tree. Here&#8217;s code using <tt class="docutils literal">ctypes</tt> to list the contents of a directory:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #00007f; font-weight: bold">from</span> <span style="color: #00007f">ctypes</span> <span style="color: #00007f; font-weight: bold">import</span> (CDLL, byref, Structure, POINTER, c_int,
                    c_void_p, c_long, c_ushort, c_ubyte,
                    c_char, c_char_p, c_void_p)

<span style="color: #007f00"># CDLL(None) invokes dlopen(NULL), which loads the currently running</span>
<span style="color: #007f00"># process - in our case Python itself. Since Python is linked with</span>
<span style="color: #007f00"># libc, readdir_r will be found there.</span>
<span style="color: #007f00"># Alternatively, we can just explicitly load &#39;libc.so.6&#39;.</span>
lib = CDLL(<span style="color: #00007f">None</span>)
<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Loaded lib {0}&#39;</span>.format(lib))

<span style="color: #007f00"># Describe the types needed for readdir_r.</span>
<span style="color: #00007f; font-weight: bold">class</span> <span style="color: #00007f">DIRENT</span>(Structure):
    _fields_ = [(<span style="color: #7f007f">&#39;d_ino&#39;</span>, c_long),
                (<span style="color: #7f007f">&#39;d_off&#39;</span>, c_long),
                (<span style="color: #7f007f">&#39;d_reclen&#39;</span>, c_ushort),
                (<span style="color: #7f007f">&#39;d_type&#39;</span>, c_ubyte),
                (<span style="color: #7f007f">&#39;d_name&#39;</span>, c_char * <span style="color: #007f7f">256</span>)]

DIR_p = c_void_p
DIRENT_p = POINTER(DIRENT)
DIRENT_pp = POINTER(DIRENT_p)

<span style="color: #007f00"># Load the functions we need from the C library. Specify their</span>
<span style="color: #007f00"># argument and return types.</span>
readdir_r = lib.readdir_r
readdir_r.argtypes = [DIR_p, DIRENT_p, DIRENT_pp]
readdir_r.restype = c_int

opendir = lib.opendir
opendir.argtypes = [c_char_p]
opendir.restype = DIR_p

closedir = lib.closedir
closedir.argtypes = [DIR_p]
closedir.restype = c_int

<span style="color: #007f00"># opendir&#39;s path argument is char*, hence bytes.</span>
path = b<span style="color: #7f007f">&#39;/tmp&#39;</span>
dir_fd = opendir(path)
<span style="color: #00007f; font-weight: bold">if</span> <span style="color: #0000aa">not</span> dir_fd:
    <span style="color: #00007f; font-weight: bold">raise</span> RuntimeError(<span style="color: #7f007f">&#39;opendir failed&#39;</span>)

dirent = DIRENT()
result = DIRENT_p()

<span style="color: #00007f; font-weight: bold">while</span> <span style="color: #00007f">True</span>:
    <span style="color: #007f00"># Note that byref() here is optional since ctypes can do it on its</span>
    <span style="color: #007f00"># own by observing the argtypes declared for readdir_r. I keep byref</span>
    <span style="color: #007f00"># for explicitness.</span>
    <span style="color: #00007f; font-weight: bold">if</span> readdir_r(dir_fd, byref(dirent), byref(result)):
        <span style="color: #00007f; font-weight: bold">raise</span> RuntimeError(<span style="color: #7f007f">&#39;readdir_r failed&#39;</span>)
    <span style="color: #00007f; font-weight: bold">if</span> <span style="color: #0000aa">not</span> result:
        <span style="color: #007f00"># If (*result == NULL), we&#39;re done.</span>
        <span style="color: #00007f; font-weight: bold">break</span>
    <span style="color: #007f00"># dirent.d_name is char[], hence we decode it to get a unicode</span>
    <span style="color: #007f00"># string.</span>
    <span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Found: &#39;</span> + dirent.d_name.decode(<span style="color: #7f007f">&#39;utf-8&#39;</span>))

closedir(dir_fd)
</pre>
</div>
<p>Here I went one step farther and actually described the required argument types for imported functions. Once again, this only helps us avoid errors to some extent. You&#8217;ll have to agree that the code is tedious. Using <tt class="docutils literal">cffi</tt>, we can just &quot;copy paste&quot; the C declarations and focus on actual calling:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #00007f; font-weight: bold">from</span> <span style="color: #00007f">cffi</span> <span style="color: #00007f; font-weight: bold">import</span> FFI

ffi = FFI()
ffi.cdef(<span style="color: #7f007f">&quot;&quot;&quot;</span>
<span style="color: #7f007f">    typedef void DIR;</span>
<span style="color: #7f007f">    typedef long ino_t;</span>
<span style="color: #7f007f">    typedef long off_t;</span>

<span style="color: #7f007f">    struct dirent {</span>
<span style="color: #7f007f">        ino_t          d_ino;       /* inode number */</span>
<span style="color: #7f007f">        off_t          d_off;       /* offset to the next dirent */</span>
<span style="color: #7f007f">        unsigned short d_reclen;    /* length of this record */</span>
<span style="color: #7f007f">        unsigned char  d_type;      /* type of file; not supported</span>
<span style="color: #7f007f">                                       by all file system types */</span>
<span style="color: #7f007f">        char           d_name[256]; /* filename */</span>
<span style="color: #7f007f">    };</span>

<span style="color: #7f007f">    DIR *opendir(const char *name);</span>
<span style="color: #7f007f">    int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);</span>
<span style="color: #7f007f">    int closedir(DIR *dirp);</span>
<span style="color: #7f007f">&quot;&quot;&quot;</span>)

<span style="color: #007f00"># Load symbols from the current process (Python).</span>
lib = ffi.dlopen(<span style="color: #00007f">None</span>)
<span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Loaded lib {0}&#39;</span>.format(lib))

path = b<span style="color: #7f007f">&#39;/tmp&#39;</span>
dir_fd = lib.opendir(path)
<span style="color: #00007f; font-weight: bold">if</span> <span style="color: #0000aa">not</span> dir_fd:
    <span style="color: #00007f; font-weight: bold">raise</span> RuntimeError(<span style="color: #7f007f">&#39;opendir failed&#39;</span>)

<span style="color: #007f00"># Allocate the pointers passed to readdir_r.</span>
dirent = ffi.new(<span style="color: #7f007f">&#39;struct dirent*&#39;</span>)
result = ffi.new(<span style="color: #7f007f">&#39;struct dirent**&#39;</span>)

<span style="color: #00007f; font-weight: bold">while</span> <span style="color: #00007f">True</span>:
    <span style="color: #00007f; font-weight: bold">if</span> lib.readdir_r(dir_fd, dirent, result):
        <span style="color: #00007f; font-weight: bold">raise</span> RuntimeError(<span style="color: #7f007f">&#39;readdir_r failed&#39;</span>)
    <span style="color: #00007f; font-weight: bold">if</span> result[<span style="color: #007f7f">0</span>] == ffi.NULL:
        <span style="color: #007f00"># If (*result == NULL), we&#39;re done.</span>
        <span style="color: #00007f; font-weight: bold">break</span>
    <span style="color: #00007f; font-weight: bold">print</span>(<span style="color: #7f007f">&#39;Found: &#39;</span> + ffi.string(dirent.d_name).decode(<span style="color: #7f007f">&#39;utf-8&#39;</span>))

lib.closedir(dir_fd)
</pre>
</div>
<p>I placed &quot;copy paste&quot; in quotes on purpose, because the man page for <tt class="docutils literal">readdir_r</tt> doesn&#8217;t fully specify all the <tt class="docutils literal">typedef</tt> declarations inside <tt class="docutils literal">struct dirent</tt>. For example, you need to do some digging to discover that <tt class="docutils literal">ino_t</tt> is <tt class="docutils literal">long</tt>. <tt class="docutils literal">cffi</tt>&#8216;s other goal, the <em>API level</em>, is to enable Python programmers to skip such declarations and let the C compiler complete the details. But since this requires a C compiler, I see it as a very different solution from the <em>ABI level</em>. In fact, it&#8217;s not really a FFI at this point, but rather an alternative way for writing C extensions to Python code.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/03/09/python-ffi-with-ctypes-and-cffi/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Flexible runtime interface to shared libraries with libffi</title>
		<link>http://eli.thegreenplace.net/2013/03/04/flexible-runtime-interface-to-shared-libraries-with-libffi/</link>
		<comments>http://eli.thegreenplace.net/2013/03/04/flexible-runtime-interface-to-shared-libraries-with-libffi/#comments</comments>
		<pubDate>Mon, 04 Mar 2013 13:36:09 +0000</pubDate>
		<dc:creator>eliben</dc:creator>
				<category><![CDATA[C / C++]]></category>
		<category><![CDATA[Plugins]]></category>

		<guid isPermaLink="false">http://eli.thegreenplace.net/?p=3108</guid>
		<description><![CDATA[Calling code from shared libraries in C is simple with dlopen / dlsym (LoadLibrary on Windows). I provided a comprehensive example in the article on Plugins in C; here, I&#8217;ll start with a simplified example. Here&#8217;s a sample C library compiled into libsomelib.so. First, the header file somelib.h: #ifndef SOMELIB_H #define SOMELIB_H typedef struct { [...]]]></description>
			<content:encoded><![CDATA[<p>Calling code from shared libraries in C is simple with <tt class="docutils literal">dlopen</tt> / <tt class="docutils literal">dlsym</tt> (<tt class="docutils literal">LoadLibrary</tt> on Windows). I provided a comprehensive example in the <a class="reference external" href="http://eli.thegreenplace.net/2012/08/24/plugins-in-c/">article on Plugins in C</a>; here, I&#8217;ll start with a simplified example.</p>
<p>Here&#8217;s a sample C library compiled into <tt class="docutils literal">libsomelib.so</tt>. First, the header file <tt class="docutils literal">somelib.h</tt>:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #007f00">#ifndef SOMELIB_H</span>
<span style="color: #007f00">#define SOMELIB_H</span>

<span style="color: #00007f; font-weight: bold">typedef</span> <span style="color: #00007f; font-weight: bold">struct</span> {
    <span style="color: #00007f; font-weight: bold">int</span> num;
    <span style="color: #00007f; font-weight: bold">double</span> dnum;
} DataPoint;

DataPoint add_data(<span style="color: #00007f; font-weight: bold">const</span> DataPoint* dps, <span style="color: #00007f; font-weight: bold">unsigned</span> n);

<span style="color: #007f00">#endif /* SOMELIB_H */</span>
</pre>
</div>
<p>And the implementation, <tt class="docutils literal">somelib.c</tt>:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #007f00">#include &quot;somelib.h&quot;</span>

DataPoint <span style="color: #00007f">add_data</span>(<span style="color: #00007f; font-weight: bold">const</span> DataPoint* dps, <span style="color: #00007f; font-weight: bold">unsigned</span> n) {
    DataPoint out = {.num = <span style="color: #007f7f">0</span>, .dnum = <span style="color: #007f7f">0.0</span>};

    <span style="color: #00007f; font-weight: bold">for</span> (<span style="color: #00007f; font-weight: bold">unsigned</span> i = <span style="color: #007f7f">0</span>; i &lt; n; ++i) {
        out.num += dps[i].num;
        out.dnum += dps[i].dnum;
    }

    <span style="color: #00007f; font-weight: bold">return</span> out;
}
</pre>
</div>
<p>Dynamically loading <tt class="docutils literal">libsomelib.so</tt> at runtime and calling <tt class="docutils literal">add_data</tt> from C code is straightforward:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #007f00">#include &lt;dlfcn.h&gt;</span>
<span style="color: #007f00">#include &lt;stdio.h&gt;</span>
<span style="color: #007f00">#include &lt;stdlib.h&gt;</span>

<span style="color: #007f00">#include &quot;somelib.h&quot;</span>

<span style="color: #007f00">// Prototype for a function pointer for add_data</span>
<span style="color: #00007f; font-weight: bold">typedef</span> DataPoint (*add_data_fn_t)(<span style="color: #00007f; font-weight: bold">const</span> DataPoint* dps, <span style="color: #00007f; font-weight: bold">unsigned</span> n);

<span style="color: #00007f; font-weight: bold">int</span> <span style="color: #00007f">main</span>(<span style="color: #00007f; font-weight: bold">int</span> argc, <span style="color: #00007f; font-weight: bold">const</span> <span style="color: #00007f; font-weight: bold">char</span>* argv[])
{
    <span style="color: #00007f; font-weight: bold">void</span>* libhandle = dlopen(<span style="color: #7f007f">&quot;./libsomelib.so&quot;</span>, RTLD_LAZY);
    <span style="color: #00007f; font-weight: bold">if</span> (!libhandle) {
        fprintf(stderr, <span style="color: #7f007f">&quot;dlopen error: %s\n&quot;</span>, dlerror());
        exit(<span style="color: #007f7f">1</span>);
    }

    printf(<span style="color: #7f007f">&quot;dlopen success: handle %p\n&quot;</span>, libhandle);

    <span style="color: #007f00">// We know the prototype of add_data so we can directly assign it to a</span>
    <span style="color: #007f00">// function pointer of the correct type.</span>
    add_data_fn_t add_data_fn = dlsym(libhandle, <span style="color: #7f007f">&quot;add_data&quot;</span>);
    <span style="color: #00007f; font-weight: bold">char</span>* err = dlerror();
    <span style="color: #00007f; font-weight: bold">if</span> (err) {
        fprintf(stderr, <span style="color: #7f007f">&quot;dlsym failed: %s\n&quot;</span>, err);
        exit(<span style="color: #007f7f">1</span>);
    }

    DataPoint dp[<span style="color: #007f7f">4</span>] = {{<span style="color: #007f7f">2</span>, <span style="color: #007f7f">2.2</span>}, {<span style="color: #007f7f">3</span>, <span style="color: #007f7f">3.3</span>}, {<span style="color: #007f7f">4</span>, <span style="color: #007f7f">4.4</span>}, {<span style="color: #007f7f">5</span>, <span style="color: #007f7f">5.5</span>}};

    printf(<span style="color: #7f007f">&quot;Calling add_data\n&quot;</span>);
    DataPoint dout = add_data_fn(dp, <span style="color: #00007f; font-weight: bold">sizeof</span>(dp) / <span style="color: #00007f; font-weight: bold">sizeof</span>(DataPoint));

    printf(<span style="color: #7f007f">&quot;dout = {%d, %lf}\n&quot;</span>, dout.num, dout.dnum);
    <span style="color: #00007f; font-weight: bold">return</span> <span style="color: #007f7f">0</span>;
}
</pre>
</div>
<p>This works great. However, note a certain lack of flexibility. While the shared library can be discovered and loaded at runtime, the interface of the function we call from it has to be defined statically, <em>at compile time</em> &#8211; this is the function pointer prototype in the snippet above.</p>
<p>But what if we want the interface to be dynamic as well? In other words, what if we don&#8217;t know <em>until runtime</em> what arguments the called function accepts? Alas, if standard C is all we have, we&#8217;re stuck. The problem is that to call a function properly, the compiler has to know what arguments it accepts to translate the call to the proper machine code sequence according to the system&#8217;s calling convention. When I disassemble both <tt class="docutils literal">add_data</tt> and the call in <tt class="docutils literal">main</tt>, I see this call sequence, which is in accordance with the System V AMD64 ABI <a class="footnote-reference" href="#id3" id="id1">[1]</a>:</p>
<ul class="simple">
<li><tt class="docutils literal">dps</tt> is passed in <tt class="docutils literal">%rdi</tt></li>
<li><tt class="docutils literal">n</tt> is passed in <tt class="docutils literal">%esi</tt></li>
<li>return value is in <tt class="docutils literal">%xmm0</tt></li>
</ul>
<p>So to call a function whose signature is determined at runtime, we&#8217;d have to implement the calling convention ourselves, packing the arguments into registers and stack as appropriate and unpacking the return value. Moreover, this has to be implemented for each platform the code runs on. And it goes beyond saying that such code is not portable since standard C does not provide direct access to the stack or to the registers.</p>
<p>Luckily, a library exists that implements all of this for us.</p>
<div class="section" id="libffi">
<h3>libffi</h3>
<p><tt class="docutils literal">libffi</tt> was designed to solve precisely the problem described above &#8211; provide a means to call a function from a shared object, while deciding <em>at runtime</em> which arguments the function accepts and which value it returns. Conceivably this can be useful for C code dynamically invoking other C code <a class="footnote-reference" href="#id4" id="id2">[2]</a>, but the main users of <tt class="docutils literal">libffi</tt> are dynamic VM languages. Python uses <tt class="docutils literal">libffi</tt> in its <tt class="docutils literal">ctypes</tt> library, and other languages like Java, Ruby and Scheme use it in similar C FFI (Foreign Function Interface) libraries.</p>
<p>Without further ado, here&#8217;s a version of the main program from above that uses <tt class="docutils literal">libffi</tt> to call <tt class="docutils literal">add_data</tt> from its shared library:</p>
<div class="highlight" style="background: #ffffff">
<pre style="line-height: 125%"><span style="color: #007f00">#include &lt;dlfcn.h&gt;</span>
<span style="color: #007f00">#include &lt;ffi.h&gt;</span>
<span style="color: #007f00">#include &lt;stdio.h&gt;</span>
<span style="color: #007f00">#include &lt;stdlib.h&gt;</span>

<span style="color: #007f00">#include &quot;somelib.h&quot;  // For the DataPoint type.</span>

<span style="color: #00007f; font-weight: bold">int</span> <span style="color: #00007f">main</span>(<span style="color: #00007f; font-weight: bold">int</span> argc, <span style="color: #00007f; font-weight: bold">const</span> <span style="color: #00007f; font-weight: bold">char</span>* argv[])
{
    <span style="color: #00007f; font-weight: bold">void</span>* libhandle = dlopen(<span style="color: #7f007f">&quot;./libsomelib.so&quot;</span>, RTLD_LAZY);
    <span style="color: #00007f; font-weight: bold">if</span> (!libhandle) {
        fprintf(stderr, <span style="color: #7f007f">&quot;dlopen error: %s\n&quot;</span>, dlerror());
        exit(<span style="color: #007f7f">1</span>);
    }

    printf(<span style="color: #7f007f">&quot;dlopen success: handle %p\n&quot;</span>, libhandle);

    <span style="color: #007f00">// Assuming we don&#39;t know the prototype of add_data at compile-time, we</span>
    <span style="color: #007f00">// have to save the output of dlsym in a void* and then prepare the</span>
    <span style="color: #007f00">// calling sequence using libffi.</span>
    <span style="color: #00007f; font-weight: bold">void</span>* add_data_fn = dlsym(libhandle, <span style="color: #7f007f">&quot;add_data&quot;</span>);
    <span style="color: #00007f; font-weight: bold">char</span>* err = dlerror();
    <span style="color: #00007f; font-weight: bold">if</span> (err) {
        fprintf(stderr, <span style="color: #7f007f">&quot;dlsym failed: %s\n&quot;</span>, err);
        exit(<span style="color: #007f7f">1</span>);
    }

    <span style="color: #007f00">// Describe the function arguments. Note that ffi_type_pointer is used</span>
    <span style="color: #007f00">// for any C pointer (the pointee type does not matter in the ABI).</span>
    ffi_type* args[] = {&amp;ffi_type_pointer, &amp;ffi_type_uint};

    <span style="color: #007f00">// Describe the DataPoint struct to libffi. Elements are described by a</span>
    <span style="color: #007f00">// NULL-terminated array of pointers to ffi_type.</span>
    ffi_type* dp_elements[] = {&amp;ffi_type_sint, &amp;ffi_type_double, <span style="color: #00007f">NULL</span>};
    ffi_type dp_type = {.size = <span style="color: #007f7f">0</span>, .alignment = <span style="color: #007f7f">0</span>,
                        .type = FFI_TYPE_STRUCT, .elements = dp_elements};

    <span style="color: #007f00">// Describe the interface of add_data to libffi.</span>
    ffi_cif cif;
    ffi_status status = ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, <span style="color: #007f7f">2</span>, &amp;dp_type,
                                     args);
    <span style="color: #00007f; font-weight: bold">if</span> (status != FFI_OK) {
        fprintf(stderr, <span style="color: #7f007f">&quot;ffi_prep_cif failed: %d\n&quot;</span>, status);
        exit(<span style="color: #007f7f">1</span>);
    }

    <span style="color: #007f00">// The avalues argument of ffi_call holds the addresses of arguments.</span>
    <span style="color: #007f00">// Since our first argument is a pointer itself, we can&#39;t just pass</span>
    <span style="color: #007f00">// &amp;dp (since in C &amp;array == array). So we create a pointer to dp and</span>
    <span style="color: #007f00">// pass its address.</span>
    DataPoint dp[<span style="color: #007f7f">4</span>] = {{<span style="color: #007f7f">2</span>, <span style="color: #007f7f">2.2</span>}, {<span style="color: #007f7f">3</span>, <span style="color: #007f7f">3.3</span>}, {<span style="color: #007f7f">4</span>, <span style="color: #007f7f">4.4</span>}, {<span style="color: #007f7f">5</span>, <span style="color: #007f7f">5.5</span>}};
    DataPoint* pdp = dp;
    <span style="color: #00007f; font-weight: bold">unsigned</span> nelems = <span style="color: #00007f; font-weight: bold">sizeof</span>(dp) / <span style="color: #00007f; font-weight: bold">sizeof</span>(DataPoint);
    <span style="color: #00007f; font-weight: bold">void</span>* values[] = {&amp;pdp, &amp;nelems};

    printf(<span style="color: #7f007f">&quot;Calling add_data via libffi\n&quot;</span>);
    DataPoint dout;
    ffi_call(&amp;cif, FFI_FN(add_data_fn), &amp;dout, values);

    printf(<span style="color: #7f007f">&quot;dout = {%d, %lf}\n&quot;</span>, dout.num, dout.dnum);
    <span style="color: #00007f; font-weight: bold">return</span> <span style="color: #007f7f">0</span>;
}
</pre>
</div>
<p>The code is heavily commented, so it should be easy to figure out what&#8217;s going on. I just want to focus on a few interesting points:</p>
<ul class="simple">
<li>The shared library is loaded as before. <tt class="docutils literal">dlopen</tt> and <tt class="docutils literal">dlsym</tt> are used. The result of <tt class="docutils literal">dlsym</tt> is just placed in a <tt class="docutils literal">void*</tt>, since we don&#8217;t know the actual function pointer signature at compile time.</li>
<li><tt class="docutils literal">somelib.h</tt> is included just for the definition of the <tt class="docutils literal">DataPoint</tt> type, since we want to actually pass data to <tt class="docutils literal">add_data</tt> and get a result.</li>
<li>The signature of <tt class="docutils literal">add_data</tt> is described dynamically, at runtime, by filling the <tt class="docutils literal">ffi_cif</tt> data structure.</li>
</ul>
<p>In terms of its implementation, <tt class="docutils literal">libffi</tt> does as much as possible in portable C, but eventually has to resort to assembly routines written for each architecture and calling convention it supports. There routines perform the actual register and stack modifications around the call to the given function to make sure the call conforms to the calling convention. Note also that due to this extra work, calls via <tt class="docutils literal">libffi</tt> are much slower than direct calls created by the compiler. In theory, it&#8217;s possible to use JIT-ing to dynamically generate efficient calling code once the function signature is known, but AFAIK <tt class="docutils literal">libffi</tt> does not implement this.</p>
<p><img alt="http://eli.thegreenplace.net/wp-content/uploads/hline.jpg" class="align-center" src="http://eli.thegreenplace.net/wp-content/uploads/hline.jpg" style="width: 320px; height: 5px;" /></p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup>
<col class="label" />
<col /></colgroup>
<tbody valign="top">
<tr>
<td class="label"><a class="fn-backref" href="#id1">[1]</a></td>
<td>I&#8217;ve compiled this example on my x64 Linux machine.</td>
</tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup>
<col class="label" />
<col /></colgroup>
<tbody valign="top">
<tr>
<td class="label"><a class="fn-backref" href="#id2">[2]</a></td>
<td>I&#8217;m curious to hear about use cases, though. It seems to me that if you want to call code from C and don&#8217;t even know the function signatures at compile time, other solutions (like serializing the arguments and return values, or some sort of message passing) is more commonplace.</td>
</tr>
</tbody>
</table>
</div>
]]></content:encoded>
			<wfw:commentRss>http://eli.thegreenplace.net/2013/03/04/flexible-runtime-interface-to-shared-libraries-with-libffi/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
