Linking C and R in Windows - c

I am trying to Link R and C in windows while following the instructions on this web page
http://mcglinn.web.unc.edu/blog/linking-c-with-r-in-windows/
I have R, RTOOLS and TurboC4 all in separate folders in C drive. My system is 64bits but I have tried it on both 32 and 64 bit R.
I have written the following code in C
#include <R.h>
void hello(int *n)
{ int i;
for(i=0; i<=*n; i++){
Rprintf("hello, world!this is hell though I'm enjoying it\n");
}
}
and saved with name WORLD.C on separate file the path to which is
C:\TurboC4\TC\BIN
I have also written the following R code
hello2 <- function(n) {
.C("hello", as.integer(n))
}
hello2(5)
and save it with name WORLD.R.
Now I have to prepare my window. I have downloaded RTools33.exe from here https://cran.r-project.org/bin/windows/Rtools/
and set the environment variables manually through this command
PATH=c:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin;c:\Program Files\R\R-3.2.2\bin\i386;
Then Reinstalled system
Before calling the C code in R I have to compile the C code in cmd. I write the following command to change the directory where WORLD.C is saved
cd C:\Users\TurboC4\TC\BIN
which is successful but when I try to compile
C:\Users\TurboC4\TC\BIN> R CMD SHLIB WORLD.c
I get the following error. " 'R' is not recognized as internal or external command, operable ". I have also tried to compile WORLD.C in C and got these two errors. "Unable to open #include R.h>" and "function Rprintf should have a prototype".
Setting Environment is a Problem
I think this is where I am facing problem. I have checked that Rtools33.exe is compatible with R 3.2.x and later. But I am getting the same error on CMD. I have tried different paths environments and have tried it with Different R versions like R- 3.2.2, R- 3.2.0, 2.15.3, 2.15.0. But when I write
"install.packages("RTools33") in any of these R version, I got the following warning message
Warning in install.packages :package ‘RTools33’ is not available (for R version
2.15.0)"
The reason for using different Rs is when you download RTOOLS folder there is a version file which says "Rtools Collection 3.3.0.1959". So I think maybe it a compatibility issue.
There are some instructions on Github page
https://github.com/stan-dev/rstan/wiki/Install-Rtools-for-Windows
"For installing Rtools, attention needs to be paid in a step where we can edit the system PATH so that the C++ compiler that is included in Rtools can be used by R. As indicated by the following step, we need to check this option (not manually edit the system PATH. Once the option is checked, system PATH would be edited to include important folders of Rtools by the installation process)."
So, I have uninstalled RTools and while reinstalling I have checked this option button as well and then retried but all in vein.
I have checked Sys.getenv('PATH') and got
c:\\\\\\\\Rtools\\\\\\\\gcc-4.6.3\\\\\\\\bin;c:\\\\\\\\RTools\\\\\\\\bin;
I have also tried by setting this path in
control pannel-> useraccountandfamilysafety->Useraccounts->change my
environment variable
and then creating new variable with above PATH.
I am still not able to direct R to C++ compiler. Can anybody please figure out what is my mistake?

This problem is now solved. There was just a minor mistake of defining the environment variable. The correct definition is as follows.
c:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin;c:\Program Files\R\R-3.2.2\bin\i386;

Related

CMake CPack NSIS How to pass install location to project?

I have a project written in C. Currently it's using UNIX makefiles to compile itself for Linux, but recently I've been looking into CMake, to be more portable.
The executable, when running, needs to access some asset files that are part of the project. When using makefiles, I would just compile the project with:
make prefix=/usr
make prefix=/usr install
So while the project is compiled, it knows that it will end up in /usr, and when running, it searching for its own project files there (in something like /usr/share/my-project/).
I created a very basic CMakeLists.txt, that compiles the .exe file, and installs it together with one other asset file in the install directory. I then run the following commands to create an NSIS installer for Windows:
cmake.exe --build --config Release .
cpack.exe
Which succesfully gives me the NSIS installer. When run, it shows the user a few steps, one of them is to decide where the project will be installed, which the user can modify.
So my question is, at that point the project has already been compiled, so how can I pass to my project its own install location, so it can access files included in the project? How do other projects do this? I couldn't find much information online about it, which makes me think I might be taking the wrong approach.
For anyone stuck in a similar problem, I found one solution.
Upon looking online, this seems to be something not recommended for Unix systems, and setting the install location during compilation is pretty standard.
For windows, however, I found the function GetModuleFileNameW (GetModuleFileNameW function (libloaderapi.h)).
It returns the path to the current executable (something like C:\Program Files\<my-app>\bin\my-app.exe). I've confirmed it returns the right path, even when I install the project on different directories. It returns the result using wchar_t, so unicode directories are also supported.
Here is a small example of how it can be used:
// to keep the example simple, this is assuming maximum 1000 characters in the path
wchar_t dynamicProjectLocationW[1000];
GetModuleFileNameW(NULL, dynamicProjectLocationW, 999);
dynamicProjectLocationW[999] = L'\0';
// given a path like "C:\X\Y\bin\myapp.exe" find the second to last slash
// so we can get the path "C:\X\Y\"
wchar_t *pointer = dynamicProjectLocationW;
wchar_t *secondToLastSlash = 0;
wchar_t *lastSlash = 0;
while (pointer[0] != L'\0') {
if (pointer[0] == L'\\') {
secondToLastSlash = lastSlash;
lastSlash = pointer;
}
pointer++;
}
// cut the path short, so we can use the project path to find other files
if (secondToLastSlash) {
secondToLastSlash++;
secondToLastSlash[0] = L'\0';
}
This is solving my problem for now, so I'll be using this until a better solution is found.

How to Use MuJoCo on Windows

This is a very easy question, but I'm struggling unreasonably hard to find answers online.
DeepMind just made MuJoCo free, so I decided to download it on my Windows computer and test it out. When I install, however, all I get is a folder.
I've created a different folder (not inside the downloaded folder), and copy pasted the hello.xml and hello.c files from the tutorial into this new folder. However, VSCode has underlined #include "mujoco.h" in red inside hello.c with the warning cannot open source file "mujoco.h".
I assume that I need to add some things to my path or somehow make my compiler able to find the header file. How should I go about doing this?
Overall, I want to be able to run hello.c.
(I have looked at many different links, which I can link here to prove I've researched elsewhere if needed, but most resources online seem to either 1. Assume things will just work / that you have experience with C and library importing 2. Are for Macs/Linux or 3. Are for mujoco-python)
TL;DR
Create empty visual C++ project
Copy the code
Add MuJoCo Header files via VCC++ Directories -> Include Directories (make sure the set the platform to x64)
Add Library Directories of Mujoco installation ("bin" directory) via Linker -> Input -> Additional Library Directories.
Add the library names (glfw3.lib, mujoco200.lib... etc.) via Linker -> General -> Additional Dependencies
Compile
Put the resulting exe into the bin dir of the MuJoCo installation
Create the project
Open Visual Studio File -> New -> Project -> Visual C++ -> Empty Project
Write the Code
stackoverflowMuJoCo -> Source Files -> Add New Item -> C++ File (I called it "main.cpp" but it shouldn't matter)
Copy the code from hello.c into main.cpp
#include "mujoco.h"
#include "stdio.h"
char error[1000];
mjModel* m;
mjData* d;
int main(void)
{
// activate MuJoCo
mj_activate("mjkey.txt");
// load model from file and check for errors
m = mj_loadXML("../model/hello.xml", NULL, error, 1000);
if( !m )
{
printf("%s\n", error);
return 1;
}
// make data corresponding to model
d = mj_makeData(m);
// run simulation for 10 seconds
while( d->time<10 )
mj_step(m, d);
// free model and data, deactivate
mj_deleteData(d);
mj_deleteModel(m);
mj_deactivate();
return 0;
}
*note i downloaded it before deepmind took over it so I still need to use the mj_activate call but you can just ignore it.
Also i change the path to hello.xml because later i am going to copy the executable into the bin dir of the MuJoCo installation(see below)
Add the header files
Right Click on the Project -> Properties
Change Configuration from whatever is selected (most likely Debug/x86) to "All Configurations" and set the Platform to x64*
VCC++ Directories -> Include Directories
Add the include directories of your MuJoCo installation "mujoco200_win64\mujoco200_win64\include" (should be a path like this)
*this makes sure you don't have to repeat the whole process for every configuration.
VSCode has underlined #include "mujoco.h" in red inside hello.c
This should now be gone.
Add the libraries
Right Click on the Project -> Properties
Configuration Properties -> Linker -> Input -> Additional Dependencies
Enter the names of the .lib files located in your "installation" of MuJoCo
Linker -> General -> Additonal Library Directories add the "mujoco200_win64\mujoco200_win64\bin" directory
The compilation should now succeed but the execution will probably fail
Execution and Debugging
At this stage the execution will probably fail with the following errors message.
To solve this you can just copy the outputed exe file stackoverflowMuJoCo\x64\Release\stackOverflowMuJoCo.exe into the bin directory of your MuJoCo installation.
This will make sure it can find the required dll's.
If you want to be able to debug: manually copy all the dll files into the "stackoverflowMuJoCo\x64\Debug" directory.
Warning
The code from the hello world example is passive simulation this means you won't see anything on the screen.
If you want to see something replace the code with this: https://github.com/atabakd/MuJoCo-Tutorials/blob/master/src/0_preliminaries/pd.cpp and add the invertedPendulum.xml to the models directory.
Some notes
There is probably a better/easier workflow but right now I just tried to get it to work. Also I used a different version of MuJoCo than you but it should basically work the same way (except for the activation stuff).
Installing the C version of MuJoCo 2.2.1 on windows and compiling/running code
(A) Installing MuJoCo and loading a model file
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A1) Navigate to https://github.com/deepmind/mujoco/releases
and download the windows installation, mujoco-2.2.1-windows-x86_64.zip
Unzip this file and put it in a good location (e.g., Documents)
A2) Navigate to bin folder and double click “simulate”. This will open up a GUI.
A3) To load a model, go to the model folder and drop an xml, say humanoid.xml onto the open window. If everything worked fine, you should see a humanoid in the window
(B) Compiling the C programs provided by Deepmind
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
B1) Assuming you have done A1) above
B2) Download the Visual Studio Installer (select community version) here: https://visualstudio.microsoft.com/downloads/
Once the installer has downloaded, run it. When prompted to choose programs, choose the one that says “Desktop development with C++” (see screenshot below). Please restart your computer after installation.

B3) Now we will get some additional libraries to compile and create executables for mujoco on windows. Go to https://github.com/glfw/glfw/releases and download the latex version for Windows (usually glfw-3.x.x.bin.WIN64.zip). Unzip the file.
Now we will drag and drop some files from the glfw folder to mujoco
i) Copy the entire include/GLFW subdirectory to mujoco/include/GLFW.
ii) Copy glfw3dll.lib from the subdirectory corresponding into your compiler (here the compiler is lib-vc2022) to mujoco/lib/glfw3dll.lib.
iii) Copy glfw3.dll from the subdirectory corresponding into your compiler (here the compiler is lib-vc2022) to mujoco/bin/glfw3.dll.
B4) We will open the x64 shell to compile and run MuJoCo. Go to: Start (bottom left corner) —> Visual studio —> x64_Native Tools Command Prompt.
From this shell navigate to the sample folder. Then type make or nmake.
B5) Navigate to bin folder. (cd .. followed by cd bin). Then type simulate. Now you can do A3) above.
This video explains these steps: https://youtu.be/u6tNfvLXK-I

"cannot open source file "vcruntime_string.h" (dependency of "string.h")" in VS Code

I am trying to learn C programming. And I am using VS Code for running almost everything.
But none of my C Codes execute. The c_cpp_properties.json is configured with the MinGW header files library path included in the "msvc-x64" section. It says "cannot open source file "vcruntime_string.h" (dependency of "string.h")" all the time.
First of all, it's weird that it is not letting you compile by not finding string.h dependency. I suggest to try the following:
Try compiling your files either with gcc or g++ (depending on the language you're using) directly from the terminal, to see if you get the "a.out" file.
Ex: Open your terminal. Find your .c files (if you're programming in C) gcc *.c then ./a.out
Try using CodeBlocks, Build and Run to see if you get the same error.
If 1 or 2 worked, it means your VS software didn't like something when you made the installation process. Reinstall VS.
I had the same problem.
I solved it just by reloading the window.
You can either press Ctrl + R or type "Developer: Reload Window" in the command palette.
You can open the command palette either by pressing Ctrl + Shift + P or going to "View"(up left corner) then "Command Palette..."

Compilation error on include with ljpeg library in C

I have a project for college, where i need to use libjpeg (C language), to complete 2 codes the teacher gave to us. It's a about transforming a pic into ASCII symbols (like the ASCII draws, you know)
We have a code for reading a jpg and a code for writing a jpg.
The problem is i had to install the libjpeg, i THINK the installation went well but i'm not sure so i have 2 questions
How can i verify libjpeg is correctly installed ? i didn't link it to gcc so i have to use the option for saying to gcc where is jpeg-6b (the folder which contains ljpeg) so i tried this :
Typing "gcc -L/jpeg-6b" the folder is jpeg-6b and it's right on the location where i do the command. i only get an error message about the fact the input is empty (normal ok), i think if the lib was not correctly installed, i should get an error for saying me i can't use the libjpeg version, right ?
In the 2 codes i said the teacher gave to us, she puts #include <libjpeg> on the beginning of it. But i saw on the internet that people use #include <jpeglib.h>, but both of them DON'T work and i get a message telling me :
test.c:1:21: fatal error: jpeglib.h: no such file or directory
#include <jpeglib.h>
is my include bad? or is the libjpeg bad installed ? (i read the doc and i did ./configure then make like it's said)
Just as you add -L/jpeg-6b you need -I/jpeg-6b/path/to/jpeg/headers too. I would recommend a Makefile to automate this.

Installing a new library in Linux, and accessing it from my C code

I am working on a project which requires me to download and use this. Inside the downloaded folder, when extracted I am presented with three things:
A folder called "include"
A folder called "src"
A file called "Makefile"
After some research, I found out that I have to navigate to the directory which contains these files, and just type in the command make.
It seemed to install the library in my system. So I tried a sample bit of code which should use the library:
csp_conn_t * conn;
csp_packet_t * packet;
csp_socket_t * socket = csp_socket(0);
csp_bind(socket, PORT_4);
csp_listen(socket, MAX_CONNS_IN_Q);
while(1) {
conn = csp_accept(socket, TIMEOUT_MAX);
packet = csp_read(conn, TIMEOUT_NONE);
printf(“%S\r\n”, packet->data);
csp_buffer_free(packet);
csp_close(conn);
}
That's all that was given for the sample server end of the code. So I decided to add these to the top:
#include <csp.h>
#include <csp_buffer.h>
#include <csp_config.h>
#include <csp_endian.h>
#include <csp_interface.h>
#include <csp_platorm.h>
Thinking I was on the right track, I tried to compile the code with gcc, but I was given this error:
csptest_server.c:1: fatal error: csp.h: No such file or directory
compilation terminated.
I thought I may not have installed the library correctly after all, but to make sure, I found out I could check by running this command, and getting this result:
find /usr -iname csp.h
/usr/src/linux-headers-2.6.35-28-generic/include/config/snd/sb16/csp.h
/usr/src/linux-headers-2.6.35-22-generic/include/config/snd/sb16/csp.h
So it seems like the csp.h is installed, maybe I am referencing it incorrectly in the header include line? Any insight? Thanks a lot.
The make command is probably only building the library, but not installing it. You could try sudo make install. This is the "common" method, but I recommend you to check the library's documentation, if any.
The sudo command is only necessary if you have no permissions to write the system's include and library directories, which may be your case.
Another possibility (instead of installing the library) is telling GCC the location of the library's source code and generated binaries (by means of the -I and -L options of the gcc command.
That Makefile will not install anything, just translate the source into a binary format.
The csp.h in the Linux kernel has nothing to do with your project, it's just a naming collision, likely to happen with three letter names.
In your case, I would presume you need to add the include directory to the compilation flags for your server, like gcc -I/path/to/csp/include/csp csptest_server.c.
(Next, you'll run into linker errors because you'll also want to specify -L/path/to/csp -lcsp so that the linker can find the binary code to link to.)

Resources