Delphi is not the most natural choice to make DLL's for R in, because R is based on C. When your DLL's will contain a lot of pointer gymnastics it is a little clumbsy because Object Pascal does not allow much pointer arithmitic.
Anyway, it can be done. Here is the source code for the Max function. Notice
library MyMaxLib; // File MyMax.pas // This is a DLL with an R-style interface ... // it exports the MyMax function. uses SysUtils, Classes; type pD = ^Double; procedure MyMax(X,Y,Z: pD); stdcall; begin if (X^ < Y^) then Z^:=Y^ else Z^:= X^; end; exports MyMax index 1; begin end.
To compile this into a DLL, execute "dcc32 MyMax.pas" from the command prompt (assuming that the source code is residing in MyMax.pas)
To call this from R, you need a wrapper. Here's one, called test.r
# Set-up test of the MyMax DLL setwd("c:/uht/Delphi/R-DLL") # ... replace with the proper path dyn.load("MyMax.dll") MyMax <- function(a,b) { c <- as.integer(0); ans <- .C("MyMax", as.double(a), as.double(b), as.double(c) ) ans[[3]] } MyMax(12,23.1)
Notice the explicit type-casting ("as.double ..."). This is to make sure that the DLL gets what it expects, a pointer to a double.
Notice: This DLL is not "vectorised" as most R functions are and should be. What I mean is, if you call this with
> MyMax(c(12,34.1),17.1)
then you get just 17.1 - the largest of the first elements. But hey.
See the pages for the C++ environments, MicroSoft Visual C++ or Borland C++ Builder.