Search code examples
rdllimport

Dynamically load user32.dll from R & call external function


I try to access user32.dll functions in R Session. I used the code:

dyn.load("c://windows//system32//user32.dll")
.External("MessageBeep", 0L)

But R session crashes. According to documentation .External is intended to use during R package creation. However there was no prohibition to use it as shown above.

I am using Windows 8 and RStudio (1.1.453) / R (3.5.0). Could you advise a proper way to call external Windows functions from R session?


Solution

  • You are accessing the Win32 C API, thus you can load the user32.dll, and then use the Foreign {base} .C() call too access the Window32 MessageBeep function.

    ##Example Code

    dyn.load("c://windows//system32//user32.dll")
    .C("MessageBeep")
    

    ##Runtime Output

    > dyn.load("c://windows//system32//user32.dll")
    > .C("MessageBeep")
    list()
    > 
    

    You should hear the Windows Message "Beep" - Alas, I have yet to figure out how to include sounds in solutions (chuckle).

    Note: I'd also recommend you take a look at the Rcpp package, I am a big fan.