Calling C code from Python

Posted: February 14, 2013 in Development, Python
Tags: , , ,

As I recently came to a point where I wanted to use C code from a django app, I had to spent some time searching for info about that.

It was much easier than I first thought

I will start with a very tiny piece of C code, just a function and let’s name it value.c:

#include <stdio.h>

int getValue(int param1) {
    return param1;
}

I want this function to be compiled and linked as a shared library, so I run:

gcc -c -fPIC value.c -o value.o

to obtain the object file, and now let’s create the library itself:

gcc -shared -Wl,-soname,libvalue.so -o libvalue.so value.o

that will give us the library file.

Now, turn to Python, and write the code for using this C function:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Author: Fernando de Francisco
#

from ctypes import cdll
lib = cdll.LoadLibrary('./libvalue.so')

def get_value():
    print lib.getValue(5)

if __name__=='__main__':
    get_value()

And that’s pretty much it :-)

If you wish to, Github holds the code I’ve used for this article HERE.

Sublime Text Logo

Sublime Text is a text editor for code, markup and prose.

INSTALLATION

Just download it from  http://www.sublimetext.com/2 and unzip it where you prefer. In linux environmentes I usually do it on $HOME/bin/ as it’s reachable from path.

PLUGINS SETUP

Sublime Text is highly extensible through plugins. There’s no centralized site for downloading them, but there’s an easy solution:

Sublime Package Control is a complete package manager for Sublime TExt 2 that helps us to search, install, uninstall and mantain packages.

Installation takes place on console: “View -> Show Console” and paste the following line:

import urllib2,os; pf='Package Control.sublime-package'; ipp=sublime.installed_packages_path(); os.makedirs(ipp) if not os.path.exists(ipp) else None; urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler())); open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read()); print 'Please restart Sublime Text to finish installation'

Once it’s installed, please relaunch the app.

To install any plugin, push Ctrl+Shift+P (Win/Lin?) or Cmd+Shift+P (OSX) and write “package“. The set of package related options will be filtered. To update the list of plugin package select “Discover Packages“. Once they’re updated, any package can be installed with the “Install Package” option

INTERESTING PLUGINS

PYLINTER

If you’re planning to use Sublime Text for Python development, pylinter is your plugin. It needs pylint already installed on the system (pip install pylint will do) and then update the path to the liny.py file on the plugin settings.

Once it’s installed you’ll get all code violation for your python code which can be hidden if needed.

SUBLIMELINTER

Similar to the previous one, but applicable for other languages. I usually have Pylinter for Python code and this one for the rest.

GIT

Will show you the git status at the bottom bar and will let you interact with the DVCS.

DEBUGGING WITH SUBLIME TEXT AND PHP

This is a bit tricky.

INSTALL XDEBUG

sudo apt-get install php5-xdebug

Customize the xdebug settings with:

sudo gedit /etc/php5/conf.d/xdebug.ini

We will add the following settings to that file if not already present:

xdebug.remote_enable=On
xdebug.remote_host="localhost"
xdebug.remote_port=9000
xdebug.remote_handler="dbgp"

That will enable remote debugging for localhost in the port 9000. Restart Apache.

sudo service apache2 restart

INSTALL SUBLIMEXDEBUG PACKAGE

We will install SublimeXdebug? through Package Control.

Ctrl + Shift + P > install > Xdebug

Then restart your Sublime Text 2 and your system is already to start debugging.

REMOTE DEBUGGER

Install the Chrome Xdebug extension and restart Chrome. There will be a new icon at the address bar where the plugin can be enabled/disabled; but first we need to adjust the extension to use the Sublime Text sessionkey.

In Chrome go to Tools -> Extensions

And open Xdebug Helper preferences and write down “sublime.xdebug” as the session key and enabled debugging only for localhost changing the domain filter.

EXAMPLE DEBUG

In Sublime a new breakpoint can be added using Ctrl+F8 combo at the preferred line. Start debugging with Shift+F8 -> Start Debugging. Sublime will then wait for a remote debug connection.

In Chrome, navigate to the localhost page you want to debug and click on the Xdebug HElper button to set it green. Reloading the page will get it frozen; that’s because it’s already captured by Sublime.

SUBLIMEXDEBUG SHORTCUTS

  • Shift+f8: Open XDebug quick panel
  • f8: Open XDebug control quick panel when debugger is connected
  • Ctrl+f8: Toggle breakpoint
  • Ctrl+Shift+f5: Run to next breakpoint
  • Ctrl+Shift+f6: Step over
  • Ctrl+Shift+f7: Step into
  • Ctrl+Shift+f8: Step out

Thanks to @alozalv for this video. I’ve liked it so much I’ve had to share it here.

The parts that I’ve felt as more important are:

  • Saying no to the Stakeholders ideas are very important in order to avoid making the product backlog infinite.
  • It’s about to give outcome, not output… Developers usually forget that.

What do you think?

[SPANISH]

Hoy he estado viendo un vídeo gracias a @semurat. Es una pequeña charla que ofrece Martijn Verburg llamado “The Diabolical Developer”.

Mi impresión tras el visionado fue de “Ooohhh, mola“. La visión era diametralmente opuesta a lo que yo últimamente defiendo, que es el agilismo y el clean code, pero había algo de verdad en todo lo que decía… y me dejó pensativo

Esta persona del vídeo habla de aprender de ti mismo, de no gastar tiempo en reuniones ni creer en los “artesanos del software”. Dice que todo el desarrollo moderno de software es erróneo y que deberíamos programar más y hacer todo lo demás menos.

Espera, Espera… que hay algo que no cuadra…

Es cierto que hace 40 años ya se desarrollaba, pero seguro que no al nivel de cantidades de gente que se hace ahora. Las metodologías de desarrollo han venido a organizar flujos, y como siempre y como en todo, si se hace mal es difícil que funcione (lease el famoso SCRUMBUT… o sea “I use SCRUM but….”).

El agilismo no te hace mejor programador, te hace responder mejor ante cambios.

El código limpio no te hace mejor programador, hace que el trabajo en equipo sea más fácil.

Los repositorios de software no te hacen mejor programador, pero te salvan el culo.

Si tienes la suerte de trabajar en un proyecto pre-establecido en el que sólo tú desarrollas, adelante: ponte los cascos, usa tu pincho USB y haz un código super eficiente que sólo tú entiendas.

Y que la fuerza te acompañe…

Por cierto, compro lo del “vi” como editor de código…

As iPhone 5 has just been showed I’ve created a small chart with all the information we’ve got at this point. If there’s any data missing, I’d be very pleased if you tell me so that I can change it.

Taking a closer look, I can see some facts:

  • Retina display is no longer the king of displays as the dpi is a bit lower than Lumia 920.
  • Lumia phones are big and clumsy.
  • ATIV S has passed unnoticed throughout many techie webs although it is quite similar to the Galaxy S III
  • MicroSD manufacturers won’t be happy because of the lack of readers in many devices.
  • NFC is missing only in iPhone 5, so I assume it will appear in the forthcoming iPhone 5S.
  • Windows Phone 8 devices still have many details undiscovered as the OS has not been presented yet.
  • I don’t like Apple changing the connection port and not using MicroUSB. Customers won’t be happy because of the change and they will still be using a propietary connector.
  • Why doesn’t the HTC One X record video in 30fps?

I was just viewing the presentation of the new Samsung ATIV S (you can see it here) and there I can hear how the presenter talks about the new features this mobile phone has and how you can take advantage of Microsoft tools and services as you are using a Microsoft device.

That is COOL, as it is using an iPhone or iPad when you own an Apple Laptop or desktop. Everything is integrated and you feel comfortable in an environment where everything is connected.

I’d like to have this same feeling if I am a Linux User. I’d like to have services only available or that works much better when used in a Linux and some mobile environment. But I haven’t got that (yet).

Android has come to be a cross platform. it’s not related to anything else than Google, and google is a service company. So I may find as comfortable in any OS, but without the feeling of having a inter-connected set of services behind me and bound to the OS.

I must say that Android is the best platform to work with Google services, that’s for sure, but there’s no desktop OS for this Google environment so tied.

So, when I see all the developers migrating from their geek Linux machines to a way cooler (and more expensive) MacBook Pro or similar, I must admit is logical, and that I would surely do the same if I had the money :-)

Venturi Effects

Posted: August 27, 2012 in World
Tags: , ,

I’ve always liked Physics and this video is very interesting… How venturi effect is applied to commons things.

Via Microsiervos