[R] dll problem with C++ function

Carsten Dormann carsten.dormann at ufz.de
Wed Nov 3 14:47:47 CET 2010

Dear fellow R-users,

I have the problem of being unable to repeatedly use a C++-function 
within R unless by dyn.unloading/dyn.loading it after each .C call.

The C++-code (too large to attach) compiles without problem using R CMD 
SHLIB. It loads (using dyn.load("myfun.so")) and executes (via .C(myfun, 
...) ) properly. The function returns no object, only reads files from 
disk, performs calculations and later writes a file to disk.
When I now use the same line of code again to re-run the analysis (again 
via .C), I get an error message claiming a malformed input file. This 
seemingly malformed input file is absolutely correct.

When I now use dyn.unload("myfun.so") and then again 
dyn.load("myfun.so"), I can use it as before.

I have absolutely no clue what is going on here. The C++-function 
returns a 1 if run correctly and 0 otherwise. The stand-alone version 
works fine. My feeling is that R cannot deallocate the memory or somehow 
doesn't "grasp" that the dll should be freed after running.

My impression is there is a very simple reason, but I couldn't find it 
(in the Writing R Extensions or in any of the R help lists, including 

ANY hint greatly appreciated!



For what it's worth, here my system details:

R version 2.12.0 (2010-10-15)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

[1] de_DE.UTF-8/de_DE.UTF-8/C/C/de_DE.UTF-8/de_DE.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

The C++-functions starts like this:
#include <R.h>

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "stdlib.h"
#include "time.h"

#include "myhelperfunctions.h"

using namespace std;

extern "C" {

... various long C++ functions without any change for inclusion into R 
(apart from renaming "main" to "myfun")


Dr. Carsten F. Dormann
Department of Computational Landscape Ecology
Helmholtz Centre for Environmental Research-UFZ	
(Department Landschaftsökologie)
(Helmholtz Zentrum für Umweltforschung - UFZ)
Permoserstr. 15	
04318 Leipzig				

Tel: ++49(0)341 2351946
Fax: ++49(0)341 2351939
Email: carsten.dormann at ufz.de
internet: http://www.ufz.de/index.php?de=4205

Registered Office/Sitz der Gesellschaft: Leipzig
Commercial Register Number/Registergericht: Amtsgericht Leipzig, Handelsregister Nr. B 4703
Chairman of the Supervisory Board/Vorsitzender des Aufsichtsrats: MinR Wilfried Kraus
Scientific Managing Director/Wissenschaftlicher Geschäftsführer: Prof. Dr. Georg Teutsch
Administrative Managing Director/Administrativer Geschäftsführer: Dr. Andreas Schmidt

More information about the R-help mailing list