Skip to main content

a silhouette of a person's head and shoulders, used as a default avatar

C++ bindings for monotouch using SWIG

cold cold light
(c) S. Delcroix 2013
I love bindings. I've always loved them. Back in the days, I was binding gtk+ and other gobject libs to C# for fun and f-spot usage. Then I bound some obj-C libs to monotouch for a client and some for pleasure.

But last week I faced something new. I wanted to bind (for monotouch) a C++ iPhone lib for which I only received the binaries and the headers files. The component was too large to even think about doing a manual C glue code. I googled about the possible solutions and the only valuable advice was to use SWIG, without any rationale or tutorial. This is then probably a first. An explanation on why SWIG can help you for this, the problem I ran into and the solutions I found.



Mono.Cxxi is sexy, but not all-purpose

I'm not the kind of guy who blindly follows recommendations, so my first try was to use anything but SWIG. I opted for Mono.Cxxi and created a full binding in a few hours. It was really easy after I figured out the gcc-xml installation steps and caveats with clang. But when I first tried to use inside my monotouch project, it was to no avail. A quick reality-check confirmed my fears:


That being said, Mono.Cxxi is great stuff, check it out. But don't count on it for static AOT.

Go SWIG

Miguel was, once again right. SWIG was the only sensible option. I've used SWIG in the 90's for python (iirc), and it looks like the website hasn't left this era. But that's for the surface only. The tool is quite capable, is well suited for .NET and you can customise it to your liking. There's even a tutorial so I won't cover the basics. 
pro-tip: on Mac, install swig with homebrew

 1. Get the DllImports right

The first thing to get right, is the DllImportAttribute for P/Invoke. It has to be like this
[DllImport ("__Internal")]
public static extern void hello ();
You can instruct swig to do that by passing the -dllimport option
swig -c++ -csharp -dllimport __Internal

2.  Generate an obj-c++ wrapper

Swig generates glue code for you in a .cxx file. It turns out that, by simply renaming it to .mm, you get a perfectly valid Obj-C++ file. Create a new (Foo_wrapper) library project with Xcode, link both that .mm file and the includes of the original library, and you'll easily get an iPhone-suited wrapper.

3. Getting rid of the AssemblyLoadExceptions

As is, the generated code compiles with smcs but crashes with an AssemblyLoadException as soon as you try to run it on the device or the simulator. That's because some SWIG generated helpers use reverse callbacks and those callbacks are usually JIT'ed by mono, which is not possible with static AOT. The solution for this is then to tag the (autogenerated) SetPending*Exception() and CreateString() with [MonoPInvokeCallback]. I do that by patching the file after the SWIG step.

4. Putting all the pieces together

So here's a (simplified) Makefile that you can use to turn your SWIG foo.i interface file to a Foo.dll assembly wrapping and embedding your original libFoo.a and the generated libFoo_wrapper.dll

5. One last thing, set IsCxx = true

Don't forget to get your AssemblyInfo.cs right, i.e. setting IsCxx to true in your LinkWithAttribute.


Wrapping up

At this point, you should be all set and you should be able to use your native c++ library directly from within monotouch. Now you have to use your brain, mess with your foo.i file and .NET-ify a bit your API.

Would you have any issue with this, or any other binding or mobile development related stuff, contact me, I'm available for contracting.


a silhouette of a person's head and shoulders, used as a default avatar

udev и camsource

(Пере)запускалка camsource (программы для показывания картинок с веб-камер) с помощью udev:

SUBSYSTEM=="video4linux", ACTION=="add", RUN+="/usr/bin/camsource -r /etc/camsource.conf"

Запускается на старте (когда udev обнаруживается usb-устройства), и перезапускается при их перетыкании (или перетыкивании).

Можно было бы сделать более красиво, т.е. использовать события "add" и "remove" и переменную DEVICE. Однако этому мешает, во-первых, использование нескольких источников в моей конфигурации (и camsource -k выключил бы сразу все), во-вторых какой-то встроенный глюк в самой программе. Дело в том, что запускаясь, процесс почему-то уходит в состояние зомби, и в /proc/NNNNN/fd оказывается пустота. А при использовании параметра [device] код ищет процесс именно по файловым дескрипторам. Иначе говоря, этот параметр вообще не работает.

Применив фантазию к udev, можно например включать трансляцию видео-потока. Что даже удобнее, чем вписывание не комплектуемых init.d-скриптам запуска camsource, ffserver и т.п. во всякие странные места типа /etc/init.d/boot.local.

a silhouette of a person's head and shoulders, used as a default avatar

KDE Platform, Workspaces, Applications 4.10 RC3: openSUSE packages available

Following up on the announcement from KDE, the openSUSE KDE team is happy to announce the availability of 4.10 RC3 packages.  Remember that they are packages meant for testing and reporting bugs, so that the next release will be as polished as possible.

You will find the packages in the KDE:Distro:Factory repository. An updated live media based on the upcoming openSUSE 12.3 ([see previous post]({{ site.url }}/2013/01/test-the-upcoming-opensuse-12-3-and-kde-workspace-applications-and-platform-4-10-rc2)) is also available (files named KDE4-4.10.RC3) .  The openSUSE 12.2 based version is also available (files named KDE Reloaded) at the same address.

Enjoy!

the avatar of KDE at openSUSE

Replacing kio_sysinfo with kinfocenter

From openSUSE 12.3 on and currently already for the RC packages of KDE SC 4.10, kio_sysinfo will be replaced by kinfocenter. The icon for kinfocenter is still missing in the Kickoff > Computer tab but will be added soon. Until then you can start kinfocenter from the normal Kickoff menu.

The main reason for the replacement is that kio_sysinfo is basically unmaintained and hence bugs do not get fixed.

If you were using kio_sysinfo, please check whether kinfocenter provides all the info and functionality you used with kio_sysinfo. If not, post your suggestions here or to the opensuse-kde mailinglist.

Missing information from kinfocenter’s  summary I noticed so far:

  • temperatures
  • free hard disk space for each partition
  • current CPU frequency

Most info is available, even in more detail than kio_sysinfo did show it, yet not as part of the summary. E.g. graphics info, memory stats etc.

a silhouette of a person's head and shoulders, used as a default avatar

OBS tar_scm: versionformat

Сервис для OBS под названием tar_scm позволяет автоматически создавать архивы из указанных репозиториев систем контроля версий исходных кодов. Естественно, имеет много параметров, описание которых не так просто найти. На головном web-интерфейсе взаимодействие с сервисами куда-то с недавних пор вообще пропало, там хоть какие-то подсказки содержались.

versionformat — один из самых любопытных параметров, позволяющих хоть как-то оформить название архива, для последующего действия сервиса set_version.

  • Для git в это поле можно указать:
    • @PARENT_TAG@ — bash любезно заменит на ближайший тег
    • поля из --pretty=format для последнего по времени коммита — полный список внизу, какой-то смысл в данной ситуации имеют %ct %cd %h (UNIX таймштамп, дата YYYYMMDD, короткий хэш коммита), причем дефисы будут любезно удалены по дороге sed'ом (даты будут получается в духе 20121221).
  • Для mercurial (hg):
    • поля из --template для последнего по времени коммита — полный список внизу. Огромное богатство для фантазии, есть встроенная опция для latesttag. Во время написания этого текста, не было способа выдать дату в виде YYYYMMDD, без дефисов. Сейчас все дефисы удаляются sed'ом, однако последняя версия tar_scm может быть еще не загружена на головной сервис.
  • svn понимает только %r — номер ревизии

  1. github: obs-service-tar_scm
  2. git show(1)
  3. hg templates
the avatar of Klaas Freitag

ownCloud Client 1.2.0 beta2

Yesterday the ownCloud Client team released the ownCloud Client 1.2.0 beta 2. It includes a couple of improvements compared to beta 1 which was released before Christmas.

The release of version 1.2.0 is planned for the next week if things go smooth.

[caption id=“attachment_219” align=“alignright” width=“595”]New Sync Protocol Dialog New Sync Protocol Dialog[/caption]

In particular, the the following improvements were added:

  • Proxy authentication fixed (Basic auth, NTLM will not yet work)
  • The status dialog now provides statistics on the last sync run (via the info button). It will tell in detail which files have been synced, added or deleted.
  • Client will go offline while the server in in maintenance mode (feature available with ownCoud master only)
  • Improved SSL Certificate acceptance
  • All sizes of the new icons are available.
  • Support files > 2 GB on all platforms for uploading.
  • Fixed some minor memory leaks and again saved some server requests through optimizations.
  • Improved error reporting to the user.
  • Remove legacy theming support.

We would appreciate if you give this release a test ride. Note that because it is beta you should make extra sure to have have backups of your data.

If you want to give feedback, please use our mailing list for general discussion and the issue tracker for bug reports. Please read our new guidelines on bug reporting before!

Download Links:

Sources:

Have fun!

the avatar of Han Wen Kam

My openSUSE 12 Journal - 8: IBM Notes 9.0 public beta

I was going to install Lotus Notes 8.5.3 on openSUSE 12.2... but a good friend of mine (Lotus geek) informed me that the next great version IBM Notes 9.0 is ready as an open beta.  He challenged me to live life on the edge again and, I accepted! L-)

Link to download IBM Notes/Domino 9.0 public beta
Link to the public beta forum.

I would like to draw your attention to the fact that IBM has dropped the Lotus brand and name this new major version IBM Notes 9.0 Social Edition.  This is a great statement of intent and direction for this product/solution.

Installation:

Pre-requisite:  You will need to uninstall previous versions of Lotus Notes (if any).  Note that installing both 8.5.x and 9.0b is not supported (officially).

After you have downloaded the tarball for Notes 9.0b, untar it.  You will notice a bunch of RPMs and a smartupgrade.sh script.  Run/execute the script as root.  Its really that simple. :)

[Update on 23 Jan 2013]:  If running smartupgrade.sh script did not work for you, don't fret.  In the same directory where all the ibm_* rpms reside.  Execute, as root, zypper in ibm_*.rpm and let zypper figure out all the dependencies for you.  All good. :)

The Notes 9.0b icon can be found via Application Launcher -> Applications -> Office -> More Programs -> IBM Notes.  You can right-click and select Add to Favourites so that you don't have to navigate that much just to start it later.

Note that in your very first startup, it will launch a text console for you to accept the license... just in case you miss it and wonder why you are stuck at the splash screen and nothing happens.

Read more »

the avatar of Han Wen Kam

My openSUSE 12 Journal - 7: Printing to PDF

One more thing... that I forgot to mention in my previous entry is the topic of printing to PDF.

I'm quite surprised this capability is not included in the base openSUSE 12.2 install since we have OSS version of the Adobe PDF reader (Okular). :-/

Scenario/Use Case:
You need to print out a document directly into a PDF format file, instead of killing trees.  Some examples are:
  • Printing online receipts directly into a PDF for your electronic filing
  • Converting some page or document into PDF format using the Print function
Do note that if your document can be opened and edited in LibreOffice (comes with 12.2), and you want to convert that document into a PDF, you can do that by clicking the PDF button within LibreOffice.

Solution:

Read more »
a silhouette of a person's head and shoulders, used as a default avatar

reNIX, un tema dark para LXDE y GNOME 3.6

Como tuve un tiempo disponible, pude navegar un poco en el contenido de GNOME-Look para buscar un tema que se visualizara bien en LXDE y GNOME3.

Aunque muchos temas se derivan de Adwaita, me sorprendió ver que reNIX mantenía la estética de fondos negros y claros.

Para descargarlo, tendremos que ir a su página en GNOME-Look y descargar en archivo ZIP que contiene el tema. Después bastará con extraerlo en el directorio .themes del home de su usuario.

Ahora abriremos el gestor de apariencia de LXDE mediante el Menú del lxpanel (Menú -> Preferencias -> Personalizar apariencia).

lxapperance

En la sección de «controles» tendremos que buscar «renix-gtk-master» y aplicar los cambios.

Con esto tendremos activados los cambios y nuestro LXDE debería lucir así (o parecido):

Renix

 

the avatar of Han Wen Kam

My openSUSE 12 Journal - 6: Hello 12.2!

More than a year (12+ months) since my last entry... obviously lots have happened... BUT

Its a new year (2013), a new job, a new Laptop and a new openSUSE 12.2!  I'll stop right there before I go off on a tangent, seeing & proclaiming trends where none existed previously.:P

Details:
  • openSUSE 12.2 x86_64 (64-bit) - KDE desktop (default)
  • Toshiba Tecra R840 (Intel i5, 4Gb RAM, 320Gb Hdd, Intel HD integrated graphics)
  • Dual-boot with Windows 7 (/dev/sda1) and openSUSE (/dev/sda2)

Installation:
Smooth as silk is all I can say and something that has come to be expected. :)

Given the dual-boot setup, I created my own disk partitioning scheme.  So this step deviated from the otherwise straight-forward install (ie click next till the end).

Disk partition scheme:
  • /dev/sda1 - 100Gb - original factory installed Windows 7 (size shrunk to 100Gb)
  • /dev/sda2 - 100Gb - root partition of openSUSE 12.2 ('/') formatted to ext4
  • /dev/sda3 - 98Gb - extended partition
  • /dev/sda5 - 6Gb - SWAP partition
  • /dev/sda6 - 92Gb - common data partition formatted to NTFS (read/write for both Win7 & openSUSE 12.2)
At install time, I did not format the common data partition.  Instead, I left it blank (unformatted) and used Windows 7 to format it much later.  Once formatted, this common data partition will be known as D:\ drive on Windows 7.

Reboot into openSUSE 12.2 and use YaST Partitioner to set a mount point.  I usually mount this under /mnt/common.  Now, openSUSE 12.2 will automatically mount the common data partition in /mnt/common on boot.

The only outstanding part is that /mnt/common is accessible by root (super-user) but normal users access is troublesome.  To make /mnt/common read-writeable by normal user, I edit the mount options of /mnt/common in the /etc/fstab file.  Example, changed the options in bold from original (first line below) to the second:

/dev/disk/by-id/ata-xxxxxx-part6 /mnt/common          ntfs-3g    user,users,gid=users,fmask=133,dmask=022,locale=en_US.UTF-8 0 0

/dev/disk/by-id/ata-xxxxxx-part6 /mnt/common          ntfs-3g    uid=han,gid=users,fmask=133,dmask=022,locale=en_US.UTF-8 0 0

where han in uid=han is my normal user account on openSUSE 12.2.

There might be a more user-friendly way to do this but I did not explore since I'm comfortable editing the /etc/fstab. Readers who knows how this can be done, please feel free to leave a comment.  Thanks.


Grub vs Grub2:
I chose to stick with Grub instead of the newer Grub2 boot loader.  The reason is simple, I could easily edit the boot options via /boot/grub/menu.lst because its a text file.  In Grub2, this is non-trivial and until they have an easier editing interface, I'll stick with Grub.


Additional Software

Read more »