{"id":199704,"date":"2023-12-12T09:12:34","date_gmt":"2023-12-12T14:12:34","guid":{"rendered":"https:\/\/ibkrcampus.com\/?p=199704"},"modified":"2023-12-15T15:40:07","modified_gmt":"2023-12-15T20:40:07","slug":"wrapping-c-code-in-an-r-package","status":"publish","type":"post","link":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/","title":{"rendered":"Wrapping C Code in an R Package"},"content":{"rendered":"\n<p><em>The article &#8220;Wrapping C Code in an R Package&#8221; first appeared on <a href=\"https:\/\/jcarroll.com.au\/2023\/08\/11\/wrapping-c-code-in-an-r-package\/\">Jonathan Carroll&#8217;s blog<\/a>. <\/em><\/p>\n\n\n\n<p>Your collaborator says to you \u201cI have some code I\u2019d like to distribute to people who will probably work in R most of the time. I don\u2019t write R, but I write C. Can you package this up for me?\u201d so you have a few options: re-write the code in R, package up the C code and make it&nbsp;<em>available<\/em>&nbsp;in R, or say no. I decided to try out the second of these, and this post details how I achieved that.<\/p>\n\n\n\n<p>Before we even start,&nbsp;<a href=\"https:\/\/blog.davisvaughan.com\/posts\/2019-03-02-now-you-c-me\/\">this<\/a>&nbsp;(blog.davisvaughan.com)&nbsp;is an excellent post summarising many of the finer points involved here &#8211; go read that! Then, read some of&nbsp;<a href=\"https:\/\/github.com\/coolbutuseless\">@coolbutuseless\u2019<\/a>&nbsp;(github.com)&nbsp;<a href=\"https:\/\/github.com\/coolbutuseless\/simplecall\">various<\/a>&nbsp;(github.com)&nbsp;repositories&nbsp;<a href=\"https:\/\/github.com\/coolbutuseless\/callme\">demonstrating<\/a>&nbsp;(github.com)&nbsp;how to wrap C code into R packages. These, and many others, go much deeper into how to achieve this, but I\u2019m going to detail what I did because a) I\u2019ll want to remember, later; b) I had enough trouble piecing together what I needed between these excellent posts and some older, possibly out of date posts; and c) I&nbsp;<em>did<\/em>&nbsp;build some functionality beyond what was done in those straightforward examples.<\/p>\n\n\n\n<p>Those of you who know R really well probably know that the language itself is in no small part&nbsp;<a href=\"https:\/\/github.com\/wch\/r-source\/tree\/trunk\/src\/main\">written in C<\/a>&nbsp;(github.com). Many packages do the same, usually for performance reasons. This becomes most apparent if you install a package \u201cfrom source\u201d and see a lot of this mess fly past in your console<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>gcc -I\"\/usr\/share\/R\/include\" -DNDEBUG -I.\/pkg\/ -fvisibility=hidden -fpic -g -O2 -ffile-prefix-map=\/build\/r-base-4A2Reg\/r-base-4.1.2=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c file1.c -o file1.o<br>gcc -I\"\/usr\/share\/R\/include\" -DNDEBUG -I.\/pkg\/ -fvisibility=hidden -fpic -g -O2 -ffile-prefix-map=\/build\/r-base-4A2Reg\/r-base-4.1.2=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c file2.c -o file2.o<br>gcc -I\"\/usr\/share\/R\/include\" -DNDEBUG -I.\/pkg\/ -fvisibility=hidden -fpic -g -O2 -ffile-prefix-map=\/build\/r-base-4A2Reg\/r-base-4.1.2=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c pkg.c -o pkg.o<br>gcc -shared -L\/usr\/lib\/R\/lib -Wl,-Bsymbolic-functions -flto=auto -ffat-lto-objects -flto=auto -Wl,-z,relro -o pkg.so file1.o file2.o pkg.o -L\/usr\/lib\/R\/lib -lR<\/code><\/pre>\n\n\n\n<p>Other languages are supported, including Fortran (yet to be superseded for numerical libraries), C++, Rust, and various others. You can usually dig into the source of these if you can track down where they come from. When debugging a function call, R is happy to step through individual lines of R code. Try the following<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>debugonce(seq.default)\nseq(5)<\/code><\/pre>\n\n\n\n<p>and step through the lines of&nbsp;<code>seq.default<\/code>&nbsp;until it reaches&nbsp;<code>1L:from<\/code>&nbsp;(yes,&nbsp;<code>seq(from = x)<\/code>&nbsp;produces the values&nbsp;<code>1<\/code>&nbsp;to&nbsp;<code>from<\/code>\u2026 sigh) where it returns that value as<\/p>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>exiting from: seq.default(5)\n&#091;1] 1 2 3 4 5<\/code><\/pre>\n\n\n\n<p>When the function involves C code, though, R can\u2019t step through that because it\u2019s compiled. One of the most common ways to hit that limitation is when a function calls either&nbsp;<code>.Internal()<\/code>&nbsp;or&nbsp;<code>.Primitive()<\/code>.<\/p>\n\n\n\n<p>I went looking for a function containing one of these (there are plenty) and found&nbsp;<code>.row_names_info<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># number of rownames\n.row_names_info(mtcars)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>## &#091;1] 32<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code># the rownames themselves\n.row_names_info(mtcars, type = 0)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>##  &#091;1] \"Mazda RX4\"           \"Mazda RX4 Wag\"       \"Datsun 710\"         \n##  &#091;4] \"Hornet 4 Drive\"      \"Hornet Sportabout\"   \"Valiant\"            \n##  &#091;7] \"Duster 360\"          \"Merc 240D\"           \"Merc 230\"           \n## &#091;10] \"Merc 280\"            \"Merc 280C\"           \"Merc 450SE\"         \n## &#091;13] \"Merc 450SL\"          \"Merc 450SLC\"         \"Cadillac Fleetwood\" \n## &#091;16] \"Lincoln Continental\" \"Chrysler Imperial\"   \"Fiat 128\"           \n## &#091;19] \"Honda Civic\"         \"Toyota Corolla\"      \"Toyota Corona\"      \n## &#091;22] \"Dodge Challenger\"    \"AMC Javelin\"         \"Camaro Z28\"         \n## &#091;25] \"Pontiac Firebird\"    \"Fiat X1-9\"           \"Porsche 914-2\"      \n## &#091;28] \"Lotus Europa\"        \"Ford Pantera L\"      \"Ferrari Dino\"       \n## &#091;31] \"Maserati Bora\"       \"Volvo 142E\"<\/code><\/pre>\n\n\n\n<p>if we wanted to see what&nbsp;<code>.row_names_info()<\/code>&nbsp;does we would write<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>.row_names_info<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>## function (x, type = 1L) \n## .Internal(shortRowNames(x, type))\n## &lt;bytecode: 0x563e6bf3c890&gt;\n## &lt;environment: namespace:base&gt;<\/code><\/pre>\n\n\n\n<p>but we can\u2019t see any deeper unless we ask where that C code lives. I recommend using&nbsp;<code>pryr::show_c_source()<\/code>&nbsp;(as I did&nbsp;<a href=\"https:\/\/jcarroll.com.au\/2022\/04\/22\/where-for-loop-art-thou\/\">in a previous post<\/a>) to identify the C code for these, e.g.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>pryr::show_c_source(.Internal(shortRowNames(mtcars)))<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>shortRowNames is implemented by do_shortRowNames with op = 0\n<\/code><\/pre>\n\n\n\n<p>which opens a&nbsp;<a href=\"https:\/\/github.com\/search?q=SEXP%20attribute_hidden%20do_shortRowNames+repo:wch\/r-source&amp;type=Code\">GitHub search of a copy of the R source<\/a>&nbsp;(github.com)&nbsp;in a browser. The file we want is&nbsp;<a href=\"https:\/\/github.com\/wch\/r-source\/blob\/018816d40299e027d5d16832916019a65c1d6af2\/src\/main\/attrib.c#L190\"><code>attrib.c<\/code><\/a>&nbsp;(github.com)&nbsp;and contains the C code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SEXP do_shortRowNames(SEXP call, SEXP op, SEXP args, SEXP env)\n{\n    \/* return  n if the data frame 'vec' has c(NA, n) rownames;\n     *\t       nrow(.) otherwise;  note that data frames with nrow(.) == 0\n     *\t\thave no row.names.\n     ==&gt; is also used in dim.data.frame() *\/\n    checkArity(op, args);\n    SEXP s = getAttrib0(CAR(args), R_RowNamesSymbol), ans = s;\n    int type = asInteger(CADR(args));\n    if( type  2)\n\terror(_(\"invalid '%s' argument\"), \"type\");\n    if(type &gt;= 1) {\n\tint n = (isInteger(s) &amp;&amp; LENGTH(s) == 2 &amp;&amp; INTEGER(s)&#091;0] == NA_INTEGER)\n\t    ? INTEGER(s)&#091;1] : (isNull(s) ? 0 : LENGTH(s));\n\tans = ScalarInteger((type == 1) ? n : abs(n));\n    }\n    return ans;\n}<\/code><\/pre>\n\n\n\n<p>Fully interpreting this is beyond the scope of this post, but the links at the start of this post cover most of what\u2019s not plain C code here.<\/p>\n\n\n\n<p>I won\u2019t share my collaborator\u2019s exact code, but I can write enough C that I can create something with all the relevant features.<\/p>\n\n\n\n<p>Let\u2019s calculate&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Pythagorean_triple\">Pythagorean Triples<\/a>&nbsp;(en.wikipedia.org)! These are sets of 3 integers (whole numbers)&nbsp;<code>a<\/code>,&nbsp;<code>b<\/code>, and&nbsp;<code>c<\/code>&nbsp;such that a triangle with sides of those lengths will be a right-triangle (contains a 90 degree \/ right-angle). These have the property that<\/p>\n\n\n\n<p class=\"has-text-align-center\"><em>a<\/em><sup>2<\/sup> + <em>b<\/em><sup>2<\/sup> = <em>c<\/em><sup>2<\/sup><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1100\" height=\"1002\" data-src=\"\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/pythagoras-Jonathan-Carroll-blog-1100x1002.png\" alt=\"\" class=\"wp-image-199850 lazyload\" data-srcset=\"https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/pythagoras-Jonathan-Carroll-blog-1100x1002.png 1100w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/pythagoras-Jonathan-Carroll-blog-700x638.png 700w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/pythagoras-Jonathan-Carroll-blog-300x273.png 300w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/pythagoras-Jonathan-Carroll-blog-768x700.png 768w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/pythagoras-Jonathan-Carroll-blog-1536x1399.png 1536w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/pythagoras-Jonathan-Carroll-blog.png 1920w\" data-sizes=\"(max-width: 1100px) 100vw, 1100px\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 1100px; aspect-ratio: 1100\/1002;\" \/><\/figure>\n\n\n\n<p><em>Pythagorean theorem&nbsp;<\/em><a href=\"https:\/\/en.wikipedia.org\/wiki\/Pythagorean_theorem\">https:\/\/en.wikipedia.org\/wiki\/Pythagorean_theorem<\/a><em>&nbsp;(en.wikipedia.org)<\/em><\/p>\n\n\n\n<p>The smallest of these is&nbsp;<code>3, 4, 5<\/code>&nbsp;because<\/p>\n\n\n\n<p class=\"has-text-align-center\">3<sup>2<\/sup> + 4<sup>2<\/sup> = 9 + 16 = 25 = 5<sup>2<\/sup><\/p>\n\n\n\n<p>Generating these just happens to fit the use-case I\u2019m emulating, plus I have a whole other blog post coming up about these (stay tuned!).<\/p>\n\n\n\n<p>Some C code to generate these up to some maximum side-length, written similar to the code I received, is<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include \n#include \n#include \nint main (int argc, char *argv&#091;]) {\n  int a, b, c;\n  int maxval;\n  int ***triangles;\n  if ( argc != 2 ) {\n    printf(\"Usage: triangle max_side_length\\n\");\n    exit(EXIT_FAILURE);\n  }\n  maxval = atoi( argv&#091;1] );\n  triangles = (int ***) malloc (maxval * sizeof(int **));\n  for (a = 0; a &lt; maxval; ++a) {\n    triangles&#091;a] = (int **) malloc (maxval * sizeof(int *));\n    for (b = 0; b &lt; maxval; ++b) {\n      triangles&#091;a]&#091;b] = (int *) malloc (maxval * sizeof(int));\n      for (c = 0; c &lt; maxval; ++c) {\n        triangles&#091;a]&#091;b]&#091;c] = 0;\n      }\n    }\n  }\n  for (c = 1; c &lt;= maxval; c++) {\n    for (b = 1; b &lt;= c; b++)\n      for (a = 1; a &lt;= b; a++)\n        if ( ( pow ( a, 2 ) + pow ( b, 2 ) ) == pow ( c, 2 ) ) {\n          triangles&#091;a]&#091;b]&#091;c] = a + b + c;\n        }\n  }\n  printf(&quot;%4s\\t%4s\\t%4s\\t%4s\\n&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;sum&quot;);\n  printf(&quot;   -------------------------\\n&quot;);\n  for (c = 1; c &lt;= maxval; c++) {\n    for (b = 1; b &lt;= c; b++)\n      for (a = 1; a &lt;= b; a++)\n        if ( ( pow ( a, 2 ) + pow ( b, 2 ) ) == pow ( c, 2 ) ) {\n          printf(&quot;%4i\\t%4i\\t%4i\\t%4i\\n&quot;, a, b, c, triangles&#091;a]&#091;b]&#091;c]);\n          }\n      }\n  exit(EXIT_SUCCESS);\n}<\/code><\/pre>\n\n\n\n<p>I won\u2019t make this an entire C tutorial, but the main pieces are:<\/p>\n\n\n\n<p>Load some libraries for printing to screen, doing math, \u2026<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;math.h&gt;<\/code><\/pre>\n\n\n\n<p>Define an entrypoint function (the thing that will run when the code is run) which takes some number of character arguments&nbsp;<code>argv<\/code>, the first of which is the compiled name of the program itself<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int main (int argc, char *argv&#091;]) {<\/code><\/pre>\n\n\n\n<p>Define some variables, the most significant being&nbsp;<code>triangles<\/code>&nbsp;which is denoted as a pointer to a pointer to a pointer (!)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  int a, b, c;\n  int maxval;\n  int ***triangles;<\/code><\/pre>\n\n\n\n<p>That\u2019s a lot of redirection, but it\u2019s just creating a reference to a 3-dimensional array.<\/p>\n\n\n\n<p>Side-note: 0-indexed languages actually make a bit more sense when working with pointer math because a \u201cvector\u201d of memory addresses really only needs to \u201cpoint\u201d to the starting address, then every element is some offset away from that, so the first element of some vector&nbsp;<code>vec<\/code>&nbsp;might have some address&nbsp;<code>x<\/code>, but you can access that with&nbsp;<code>vec[0]<\/code>. You can access the next element with&nbsp;<code>vec[1]<\/code>&nbsp;which means \u201coffset 1 position from&nbsp;<code>x<\/code>, the starting address.\u201d You can access the fifth value by offsetting 4 positions, so&nbsp;<code>vec[4]<\/code>.<\/p>\n\n\n\n<p>One of my favourite bits of C trivia is that this syntactic sugar of using square brackets to identify positions actually translates to<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>vec&#091;0] is at address x + 0 =&gt; vec + 0\nvec&#091;1] is at address x + 1 =&gt; vec + 1\nvec&#091;2] is at address x + 2 =&gt; vec + 2\n...\nvec&#091;5] is at address x + 5 =&gt; vec + 5<\/code><\/pre>\n\n\n\n<p>but addition (<code>+<\/code>) is symmetric (commutative) so we can just as easily write<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>vec + 0 =&gt; 0 + vec =&gt; 0 + x is at address 0&#091;vec]\nvec + 1 =&gt; 1 + vec =&gt; 1 + x is at address 1&#091;vec]\nvec + 2 =&gt; 2 + vec =&gt; 2 + x is at address 2&#091;vec]\n...\nvec + 5 =&gt; 5 + vec =&gt; 5 + x is at address 5&#091;vec]<\/code><\/pre>\n\n\n\n<p>and it all works out\u2026&nbsp;<code>5[obj]<\/code>&nbsp;is valid, and corresponds to the same address as&nbsp;<code>obj[5]<\/code>.<\/p>\n\n\n\n<p>Back to our function. If only one argument is passed in (the name of the program) then the usage information is printed, otherwise the next argument is used to set the upper bound on the length of a side of the triangle, converting it from a string to an int with&nbsp;<code>atoi<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> if ( argc != 2 ) {\n    printf(\"Usage: triangle max_side_length\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  maxval = atoi( argv&#091;1] );<\/code><\/pre>\n\n\n\n<p>Next, the array is allocated (and assigned a default value of 0)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  triangles = (int ***) malloc (maxval * sizeof(int **));\n  for (a = 0; a &lt; maxval; ++a) {\n    triangles&#091;a] = (int **) malloc (maxval * sizeof(int *));\n    for (b = 0; b &lt; maxval; ++b) {\n      triangles&#091;a]&#091;b] = (int *) malloc (maxval * sizeof(int));\n      for (c = 0; c &lt; maxval; ++c) {\n        triangles&#091;a]&#091;b]&#091;c] = 0;\n      }\n    }\n  }<\/code><\/pre>\n\n\n\n<p>and then, finally, we do the \u2018calculation\u2019 which just involves stepping through every value, and if our criteria of<\/p>\n\n\n\n<p class=\"has-text-align-center\"><em>a<\/em><sup>2<\/sup> + <em>b<\/em><sup>2<\/sup> == <em>c<\/em><sup>2<\/sup><\/p>\n\n\n\n<p>is met, we assign the sum of these to an element in&nbsp;<code>triangles<\/code>&nbsp;indexed by&nbsp;<code>a<\/code>,&nbsp;<code>b<\/code>, and&nbsp;<code>c<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  for (c = 1; c &lt;= maxval; c++) {\n    for (b = 1; b &lt;= c; b++)\n      for (a = 1; a &lt;= b; a++)\n        if ( ( pow ( a, 2 ) + pow ( b, 2 ) ) == pow ( c, 2 ) ) {\n          triangles&#091;a]&#091;b]&#091;c] = a + b + c;\n        }\n  }<\/code><\/pre>\n\n\n\n<p>This isn\u2019t&nbsp;<em>efficient<\/em>&nbsp;at all &#8211; there will be lots of&nbsp;<code>0<\/code>&nbsp;values, but this is a simple program.<\/p>\n\n\n\n<p>The last section of the code just loops back through all of&nbsp;<code>a<\/code>,&nbsp;<code>b<\/code>, and&nbsp;<code>c<\/code>&nbsp;and when it finds a non-zero element, it prints it, along with the sum&nbsp;<code>a + b + c<\/code>&nbsp;(the value in&nbsp;<code>triangles[a][b][c]<\/code>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  printf(\"%4s\\t%4s\\t%4s\\t%4s\\n\", \"a\", \"b\", \"c\", \"sum\");\n  printf(\"   -------------------------\\n\");\n  for (c = 1; c &lt;= maxval; c++) {\n    for (b = 1; b &lt;= c; b++)\n      for (a = 1; a &lt;= b; a++)\n        if ( ( pow ( a, 2 ) + pow ( b, 2 ) ) == pow ( c, 2 ) ) {\n          printf(&quot;%4i\\t%4i\\t%4i\\t%4i\\n&quot;, a, b, c, triangles&#091;a]&#091;b]&#091;c]);\n          }\n      }<\/code><\/pre>\n\n\n\n<p>With all of this saved as&nbsp;<a href=\"https:\/\/github.com\/jonocarroll\/triangles\/blob\/main\/inst\/src\/triangles.c\"><code>triangles.c<\/code><\/a>&nbsp;(github.com)&nbsp;we can compile and run this code in a terminal<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ cc -O -o triangle triangles.c\n\n$ .\/triangle \nUsage: triangle max_side_length\n\n$ .\/triangle 16\n   a\t   b\t   c\t sum\n   -------------------------\n   3\t   4\t   5\t  12\n   6\t   8\t  10\t  24\n   5\t  12\t  13\t  30\n   9\t  12\t  15\t  36<\/code><\/pre>\n\n\n\n<p>Woot! You can even check that it has worked:<\/p>\n\n\n\n<p class=\"has-text-align-center\">9<sup>2<\/sup> + 12<sup>2<\/sup> = 81 + 144 = 225 = 15<sup>2<\/sup><\/p>\n\n\n\n<p>Back to the goal of this post &#8211; how do we get R to run that? We have some C code, now what?<\/p>\n\n\n\n<p>First, I created an R package. I like using RStudio for this as it auto-generates a lot of the structure I want. It does, however, create an example R file&nbsp;<code>R\/hello.R<\/code>&nbsp;(and corresponding&nbsp;<code>man\/hello.Rd<\/code>&nbsp;page) so I delete those. I also delete the&nbsp;<code>NAMESPACE<\/code>&nbsp;because I\u2019m going to use {roxygen} to generate a new one. I check \u2018Generate documentation with Roxygen\u2019 in the Build tools menu, making sure to select \u2018Build &amp; Reload\u2019 (which should be a default, no?)<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1100\" height=\"814\" data-src=\"\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/generate-jonathan-carroll-blog-1100x814.png\" alt=\"\" class=\"wp-image-199856 lazyload\" data-srcset=\"https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/generate-jonathan-carroll-blog-1100x814.png 1100w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/generate-jonathan-carroll-blog-700x518.png 700w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/generate-jonathan-carroll-blog-300x222.png 300w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/generate-jonathan-carroll-blog-768x568.png 768w, https:\/\/ibkrcampus.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/generate-jonathan-carroll-blog.png 1476w\" data-sizes=\"(max-width: 1100px) 100vw, 1100px\" src=\"data:image\/svg+xml;base64,PHN2ZyB3aWR0aD0iMSIgaGVpZ2h0PSIxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==\" style=\"--smush-placeholder-width: 1100px; aspect-ratio: 1100\/814;\" \/><figcaption class=\"wp-element-caption\">Generate documentation with Roxygen<\/figcaption><\/figure>\n<\/div>\n\n\n<p>and build my empty package.<\/p>\n\n\n\n<p>I&nbsp;<em>love<\/em>&nbsp;the {usethis} package for building packages, and there\u2019s support there for what we\u2019re doing, too!&nbsp;<code>usethis::use_c()<\/code>&nbsp;sets up some structure and adds the required boilerplate so that Roxygen knows we\u2019re using C code. This does add a&nbsp;<code>src\/code.c<\/code>&nbsp;file we can delete and in its place we can put our own C code.<\/p>\n\n\n\n<p>If you read the links at the start of this post, you\u2019ll recognise that this C code isn\u2019t quite ready to be used in an R package, though &#8211; we need to be able to send an R object (a&nbsp;<code>SEXP<\/code>) to this C code, not a&nbsp;<code>char<\/code>. More importantly, the functionality of the C code is all wrapped up in the&nbsp;<code>main()<\/code>&nbsp;entrypoint function &#8211; it would be great if that was refactored out to another function that could be called from&nbsp;<code>main()<\/code>&nbsp;but also from an R-facing function.<\/p>\n\n\n\n<p>I communicated this to my colleague and they agreed we could refactor that, but they want to still run the C code from the command line, so we can\u2019t just put&nbsp;<em>everything<\/em>&nbsp;in our R-facing function. The actual processing in the code could go to a new function that doesn\u2019t return anything, but does update the 3-dimensional array passed by reference<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void calculate_sum(int maxval, int ****tri_sum) {\n  int a, b, c;\n  for (c = 1; c &lt;= maxval; c++) {\n    for (b = 1; b &lt;= c; b++)\n      for (a = 1; a &lt;= b; a++)\n        if ( ( pow ( a, 2 ) + pow ( b, 2 ) ) == pow ( c, 2 ) ) {\n          (*tri_sum)&#091;a]&#091;b]&#091;c] = a + b + c;\n        }\n  }\n}\n&#091;... in main()]\n printf(&quot;calling external sum\\n&quot;);\n calculate_sum(maxval, &amp;triangles);<\/code><\/pre>\n\n\n\n<p>Yes, that\u2019s a pointer to a pointer to a pointer to a pointer (!!!!).<\/p>\n\n\n\n<p>The gotchas I encountered here were that<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>*tri_sum&#091;a]&#091;b]&#091;c]<\/code><\/pre>\n\n\n\n<p>would be a pointer to the&nbsp;<em>indexed<\/em>&nbsp;object, so I needed<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>(*tri_sum)&#091;a]&#091;b]&#091;c]<\/code><\/pre>\n\n\n\n<p>and&nbsp;<code>&amp;triangles<\/code>&nbsp;sends a reference to the&nbsp;<code>triangles<\/code>&nbsp;object.<\/p>\n\n\n\n<p>Compiling and running&nbsp;<a href=\"https:\/\/github.com\/jonocarroll\/triangles\/blob\/main\/inst\/src\/triangles1.c\">this<\/a>&nbsp;(github.com)&nbsp;shows that we\u2019ve successfully refactored out the main functionality<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ cc -O -o triangle1 triangles1.c\n\n$ .\/triangle1 20\ncalling external sum\n   a\t   b\t   c\t sum\n   -------------------------\n   3\t   4\t   5\t  12\n   6\t   8\t  10\t  24\n   5\t  12\t  13\t  30\n   9\t  12\t  15\t  36\n   8\t  15\t  17\t  40\n  12\t  16\t  20\t  48<\/code><\/pre>\n\n\n\n<p>But this still isn\u2019t&nbsp;<em>quite<\/em>&nbsp;what we need for R\u2026 we need to pass and return&nbsp;<code>SEXP<\/code>s.<\/p>\n\n\n\n<p>Rather than disrupt the runnable C code, we can add some additional R-specific code. That requires the R-related libraries<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;R.h&gt;\n#include &lt;Rinternals.h&gt;<\/code><\/pre>\n\n\n\n<p>(keeping in mind that these are&nbsp;<em>required<\/em>&nbsp;if the user is compiling all of this code &#8211; it\u2019s possible, but perhaps we\u2019ll comment these out when just using the C code standalone).<\/p>\n\n\n\n<p>We need a function that takes a&nbsp;<code>SEXP<\/code>&nbsp;(our maximum value) and returns a&nbsp;<code>SEXP<\/code>&nbsp;&#8211; this is required, but so far we\u2019re just printing to screen. We\u2019ll return&nbsp;<em>something<\/em>&nbsp;for now. A function that meets these criteria and calls the new&nbsp;<code>calculate_sum()<\/code>&nbsp;could&nbsp;<a href=\"https:\/\/github.com\/jonocarroll\/triangles\/blob\/main\/inst\/src\/triangles2.c\">be<\/a>&nbsp;(github.com)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SEXP C_triangles(SEXP maximum) {\n  int a, b, c;\n  int ***triangles;\n  int maxval = * INTEGER(maximum);\n  triangles = (int ***) malloc (maxval * sizeof(int **));\n  for (a = 0; a &lt; maxval; ++a) {\n    triangles&#091;a] = (int **) malloc (maxval * sizeof(int *));\n    for (b = 0; b &lt; maxval; ++b) {\n      triangles&#091;a]&#091;b] = (int *) malloc (maxval * sizeof(int));\n      for (c = 0; c &lt; maxval; ++c) {\n        triangles&#091;a]&#091;b]&#091;c] = 0;\n      }\n    }\n  }\n  printf(&quot;calling C function to calc sum\\n&quot;);\n  calculate_sum(maxval, &amp;triangles);\n  printf(&quot;%4s\\t%4s\\t%4s\\t%4s\\n&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;sum&quot;);\n  printf(&quot;   -------------------------\\n&quot;);\n  for (c = 1; c &lt; maxval; ++c) {\n    for (b = 1; b &lt;= c; ++b)\n      for (a = 1; a &lt;= b; ++a)\n        if ( ( pow ( a, 2 ) + pow ( b, 2 ) ) == pow ( c, 2 ) ) {\n          printf(&quot;%4i\\t%4i\\t%4i\\t%4i\\n&quot;, a, b, c, triangles&#091;a]&#091;b]&#091;c]);\n        }\n  }\n  SEXP result = PROTECT(allocVector(LGLSXP, 1));\n  LOGICAL(result)&#091;0] = 1;\n  UNPROTECT(1);\n  return(result);\n}<\/code><\/pre>\n\n\n\n<p>This is very similar to what\u2019s in&nbsp;<code>main()<\/code>&nbsp;&#8211; it still performs the allocation then calls out to the calculating code, then prints the result. The only new part is creating a logical&nbsp;<code>result<\/code>&nbsp;object (<code>1<\/code>&nbsp;==&nbsp;<code>TRUE<\/code>) so that there\u2019s something to return.<\/p>\n\n\n\n<p>You can read about&nbsp;<code>PROTECT<\/code>&nbsp;which guards against garbage collection in the&nbsp;<a href=\"https:\/\/cran.r-project.org\/doc\/manuals\/r-release\/R-exts.html#Garbage-Collection\">R-exts manual<\/a>&nbsp;(cran.r-project.org).<\/p>\n\n\n\n<p>The new functions called here such as&nbsp;<code>allocVector<\/code>&nbsp;come from the Rinternals library and are macros for functions starting with&nbsp;<code>Rf_<\/code>&nbsp;&#8211; i.e.&nbsp;<code>Rf_allocVector<\/code>. I had some issues initially because I followed some guides which used&nbsp;<code>#define R_NO_REMAP<\/code>. Keep in mind that if you use that (so that library functions aren\u2019t remapped) you will need to use the&nbsp;<code>Rf_<\/code>&nbsp;versions of these functions. I ended up removing the&nbsp;<code>#define<\/code>&nbsp;myself, but I\u2019m not sure if that will bite me later.<\/p>\n\n\n\n<p>This also needs to convert the&nbsp;<code>SEXP<\/code>&nbsp;input&nbsp;<code>maximum<\/code>&nbsp;to a C&nbsp;<code>int<\/code>&nbsp;via&nbsp;<code>* INTEGER(maximum)<\/code>.<\/p>\n\n\n\n<p>We now have something that&nbsp;<em>should<\/em>&nbsp;work in our R package! Saving this as&nbsp;<code>src\/triangles.c<\/code>&nbsp;we can add the R interface as&nbsp;<code>R\/triangles.R<\/code>&nbsp;containing just<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#' triangles\n#'\n#' @export\ntriangles &lt;- function(maxval) {\n  .Call(\"C_triangles\", as.integer(maxval))\n}<\/code><\/pre>\n\n\n\n<p>where we definitely only send an integer to the C function.<\/p>\n\n\n\n<p>Build the package, which compiles the code, and load the package<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>library(triangles)\ntriangles(20)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>calling C function to calc sum\n   a\t   b\t   c\t sum\n   -------------------------\n   3\t   4\t   5\t  12\n   6\t   8\t  10\t  24\n   5\t  12\t  13\t  30\n   9\t  12\t  15\t  36\n   8\t  15\t  17\t  40\n&#091;1] TRUE<\/code><\/pre>\n\n\n\n<p>We see the debug print statement, then the printed output, and finally our returned&nbsp;<code>TRUE<\/code>. Success!<\/p>\n\n\n\n<p>The original code was made to work in a command line pipeline where the values were read back in by a subsequent program, e.g.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ .\/triangle 16 | tail +3 | awk '{ sum += $4 } END { print sum }'\n102<\/code><\/pre>\n\n\n\n<p>so printing to&nbsp;<code>stdout<\/code>&nbsp;made sense there, but we want to&nbsp;<em>use<\/em>&nbsp;the values in R, so it would be great to return an actual&nbsp;<code>data.frame<\/code>.&nbsp;<a href=\"https:\/\/github.com\/coolbutuseless\/simplecall\/blob\/master\/src\/create-data-frame.c\">This repo<\/a>&nbsp;(github.com)&nbsp;contains a great example of doing that but I want to return a&nbsp;<code>data.frame<\/code>&nbsp;with a variable number of rows, and I need to allocate data into that. ChatGPT actually got me close enough to a working version. Here\u2019s what I ended up with<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> &#091;...]\n  calculate_sum(maxval, &amp;triangles);\n  \/* count rows *\/\n  int nrows = 0;\n  for (c = 1; c &lt; maxval; ++c) {\n    for (b = 1; b &lt;= c; ++b)\n      for (a = 1; a &lt;= b; ++a)\n          if (triangles&#091;a]&#091;b]&#091;c] != 0) {\n          nrows += 1;\n        }\n  }\n  \/* output a data.frame *\/\n  int ncols = 4;\n  SEXP col1, col2, col3, col4, df;\n  PROTECT(df = allocVector(VECSXP, ncols));\n  PROTECT(col1 = allocVector(INTSXP, nrows));\n  PROTECT(col2 = allocVector(INTSXP, nrows));\n  PROTECT(col3 = allocVector(INTSXP, nrows));\n  PROTECT(col4 = allocVector(INTSXP, nrows));\n  int j = 0;\n  for (c = 1; c &lt; maxval; ++c) {\n    for (b = 1; b &lt;= c; ++b) {\n      for (a = 1; a &lt;= b; ++a) {\n        if (triangles&#091;a]&#091;b]&#091;c] != 0) {\n          INTEGER(col1)&#091;j] = a;\n          INTEGER(col2)&#091;j] = b;\n          INTEGER(col3)&#091;j] = c;\n          INTEGER(col4)&#091;j] = triangles&#091;a]&#091;b]&#091;c];\n          j += 1;\n        }\n      }\n    }\n  }\n  SET_VECTOR_ELT(df, 0, col1);\n  SET_VECTOR_ELT(df, 1, col2);\n  SET_VECTOR_ELT(df, 2, col3);\n  SET_VECTOR_ELT(df, 3, col4);\n  SEXP colNames;\n  PROTECT(colNames = allocVector(STRSXP, ncols));\n  SET_STRING_ELT(colNames, 0, mkChar(&quot;a&quot;));\n  SET_STRING_ELT(colNames, 1, mkChar(&quot;b&quot;));\n  SET_STRING_ELT(colNames, 2, mkChar(&quot;c&quot;));\n  SET_STRING_ELT(colNames, 3, mkChar(&quot;sum&quot;));\n  setAttrib(df, R_NamesSymbol, colNames);\n  SEXP rowNames;\n  PROTECT(rowNames = allocVector(STRSXP, nrows));\n  for (int i = 0; i &lt; nrows; ++i) {\n    char rowName&#091;11];\n    snprintf(rowName, sizeof(rowName), &quot;%10d&quot;, i + 1\n    SET_STRING_ELT(rowNames, i, mkChar(rowName));\n  }\n  setAttrib(df, R_RowNamesSymbol, rowNames);\n  SEXP className;\n  PROTECT(className = allocVector(STRSXP, 1));\n  SET_STRING_ELT(className, 0, mkChar(&quot;data.frame&quot;));\n  classgets(df, className);\n  UNPROTECT(8);\n  return df;<\/code><\/pre>\n\n\n\n<p>Going through the biggest parts of this: first we identify how many rows we want to output by counting the nonzero elements of the passed-by-reference&nbsp;<code>triangles<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> \/* count rows *\/\n  int nrows = 0;\n  for (c = 1; c &lt; maxval; ++c) {\n    for (b = 1; b &lt;= c; ++b)\n      for (a = 1; a &lt;= b; ++a)\n          if (triangles&#091;a]&#091;b]&#091;c] != 0) {\n          nrows += 1;\n        }\n  }<\/code><\/pre>\n\n\n\n<p>then allocating vectors &#8211; first a list the length of the number of columns (4) then one for each of the columns with length&nbsp;<code>nrows<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/* output a data.frame *\/\n  int ncols = 4;\n\n  SEXP col1, col2, col3, col4, df;\n  PROTECT(df = allocVector(VECSXP, ncols));\n\n  PROTECT(col1 = allocVector(INTSXP, nrows));\n  PROTECT(col2 = allocVector(INTSXP, nrows));\n  PROTECT(col3 = allocVector(INTSXP, nrows));\n  PROTECT(col4 = allocVector(INTSXP, nrows));<\/code><\/pre>\n\n\n\n<p>These are then populated in a loop with a new counter for the nonzero elements<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> int j = 0;\n  for (c = 1; c &lt; maxval; ++c) {\n    for (b = 1; b &lt;= c; ++b) {\n      for (a = 1; a &lt;= b; ++a) {\n        if (triangles&#091;a]&#091;b]&#091;c] != 0) {\n          INTEGER(col1)&#091;j] = a;\n          INTEGER(col2)&#091;j] = b;\n          INTEGER(col3)&#091;j] = c;\n          INTEGER(col4)&#091;j] = triangles&#091;a]&#091;b]&#091;c];\n          j += 1;\n        }\n      }\n    }\n  }<\/code><\/pre>\n\n\n\n<p>and finally the vectors linked into the list<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  SET_VECTOR_ELT(df, 0, col1);\n  SET_VECTOR_ELT(df, 1, col2);\n  SET_VECTOR_ELT(df, 2, col3);\n  SET_VECTOR_ELT(df, 3, col4);<\/code><\/pre>\n\n\n\n<p>The rest is mostly boilerplate of setting up the&nbsp;<code>data.frame<\/code>: assigning column names<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  SEXP colNames;\n  PROTECT(colNames = allocVector(STRSXP, ncols));\n  SET_STRING_ELT(colNames, 0, mkChar(\"a\"));\n  SET_STRING_ELT(colNames, 1, mkChar(\"b\"));\n  SET_STRING_ELT(colNames, 2, mkChar(\"c\"));\n  SET_STRING_ELT(colNames, 3, mkChar(\"sum\"));\n  setAttrib(df, R_NamesSymbol, colNames);<\/code><\/pre>\n\n\n\n<p>and row names<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> SEXP rowNames;\n  PROTECT(rowNames = allocVector(STRSXP, nrows));\n  for (int i = 0; i &lt; nrows; ++i) {\n    char rowName&#091;11];\n    snprintf(rowName, sizeof(rowName), \"%10d\", i + 1\n    SET_STRING_ELT(rowNames, i, mkChar(rowName));\n  }\n  setAttrib(df, R_RowNamesSymbol, rowNames);<\/code><\/pre>\n\n\n\n<p>and the class itself<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  SEXP className;\n  PROTECT(className = allocVector(STRSXP, 1));\n  SET_STRING_ELT(className, 0, mkChar(\"data.frame\"));\n  classgets(df, className);<\/code><\/pre>\n\n\n\n<p>then finally&nbsp;<code>UNPROTECT<\/code>ing the&nbsp;<code>PROTECTED<\/code>&nbsp;objects and returning the&nbsp;<code>data.frame<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  UNPROTECT(8);\n  return df;<\/code><\/pre>\n\n\n\n<p>At one point, I had forgotten that I had modified an example and now had more&nbsp;<code>PROTECT<\/code>&nbsp;wrappers around objects, but hadn\u2019t updated the number in&nbsp;<code>UNPROTECT<\/code>. It turns out this leads to an error in R about a stack imbalance &#8211; not particularly meaningful if you don\u2019t realise what that means, so FYI.<\/p>\n\n\n\n<p>So, with&nbsp;<a href=\"https:\/\/github.com\/jonocarroll\/triangles\/blob\/main\/inst\/src\/triangles3.c\">this new code<\/a>&nbsp;(github.com)&nbsp;in&nbsp;<code>src\/triangles.c<\/code>&nbsp;we re-build and reload and try it out<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>library(triangles)\n\nx &lt;- triangles(16)\n\nx<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>##            a  b  c sum\n##          1 3  4  5  12\n##          2 6  8 10  24\n##          3 5 12 13  30\n##          4 9 12 15  36<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>str(x)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>## 'data.frame':\t4 obs. of  4 variables:\n##  $ a  : int  3 6 5 9\n##  $ b  : int  4 8 12 12\n##  $ c  : int  5 10 13 15\n##  $ sum: int  12 24 30 36<\/code><\/pre>\n\n\n\n<p>Nothing printed when not expected, and the result is really a&nbsp;<code>data.frame<\/code>! We can even work with the data now<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sum(x$sum)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code has-light-green-cyan-background-color has-background\"><code>## &#091;1] 102<\/code><\/pre>\n\n\n\n<p>We still have the C code, and this can be updated as it evolves without affecting the R interface to it. With the R parts commented out, it can still be run as if it was just a regular C file. If we&nbsp;<em>really<\/em>&nbsp;want to compile it with the R parts still there we can include the R libraries (on a linux system, for example) with<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ cc -O -o triangle triangles.c -I\/usr\/share\/R\/include -L\/usr\/lib\/R\/lib -lR\n<\/code><\/pre>\n\n\n\n<p><strong>Update 12-Aug-2023<\/strong>: I forgot to mention that in order to pass checks, R wants to have the following, typically in a file&nbsp;<a href=\"https:\/\/github.com\/jonocarroll\/triangles\/blob\/main\/src\/init.c\"><code>src\/init.c<\/code><\/a>&nbsp;(github.com)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;R.h&gt;\n#include &lt;Rinternals.h&gt;\n#include &lt;stdlib.h&gt; \/\/ for NULL\n#include &lt;R_ext\/Rdynload.h&gt;\n\n\/* .Call calls *\/\nextern SEXP C_triangles(SEXP maximum);\n\nstatic const R_CallMethodDef CallEntries&#091;] = {\n  {\"C_triangles\", (DL_FUNC) &amp;C_triangles, 1},\n  {NULL, NULL, 0}\n};\n\nvoid R_init_addr(DllInfo *dll) {\n  R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);\n  R_useDynamicSymbols(dll, FALSE);\n}<\/code><\/pre>\n\n\n\n<p>I won\u2019t say I understand this bit, but it&nbsp;<em>is<\/em>&nbsp;mentioned in&nbsp;<a href=\"https:\/\/blog.davisvaughan.com\/posts\/2019-03-02-now-you-c-me\/#registration\">this part<\/a>&nbsp;(blog.davisvaughan.com)&nbsp;of Davis\u2019 post.<\/p>\n\n\n\n<p>I also updated the&nbsp;<code>snprintf<\/code>&nbsp;call in the rownames assignment since I got a warning about truncation.<\/p>\n\n\n\n<p>There are some valid concerns about the fact that I\u2019m not explicitly&nbsp;<code>free()<\/code>ing the allocated memory, so I plan to add some code to do that.<\/p>\n\n\n\n<p>As always, I\u2019ve learned a lot messing with things outside of my comfort zone here. I wouldn\u2019t say that I want to write a lot more C code, but at least now I feel somewhat comfortable bringing into R to work with.<\/p>\n\n\n\n<p>The package I detailed building here is on GitHub:&nbsp;<a href=\"https:\/\/github.com\/jonocarroll\/triangles\">https:\/\/github.com\/jonocarroll\/triangles<\/a>&nbsp;(github.com)&nbsp;in case it\u2019s useful to you.<\/p>\n\n\n\n<p>There\u2019s always more for me to learn, though, so if you have comments, feedback, suggestions for improvements, etc\u2026 I can be found on&nbsp;<a href=\"https:\/\/fosstodon.org\/@jonocarroll\">Mastodon<\/a>&nbsp;(fosstodon.org).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Those of you who know R really well probably know that the language itself is in no small part written in C.<\/p>\n","protected":false},"author":1279,"featured_media":199975,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[339,343,338,341,342],"tags":[2279,14403,487,16408,6591],"contributors-categories":[16353],"class_list":{"0":"post-199704","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-science","8":"category-programing-languages","9":"category-ibkr-quant-news","10":"category-quant-development","11":"category-r-development","12":"tag-c-5","13":"tag-chatgpt","14":"tag-r","15":"tag-roxygen","16":"tag-rstats","17":"contributors-categories-jonathan-carroll"},"pp_statuses_selecting_workflow":false,"pp_workflow_action":"current","pp_status_selection":"publish","acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v26.9 (Yoast SEO v27.4) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Wrapping C Code in an R Package | IBKR Quant<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.interactivebrokers.com\/campus\/wp-json\/wp\/v2\/posts\/199704\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Wrapping C Code in an R Package\" \/>\n<meta property=\"og:description\" content=\"Those of you who know R really well probably know that the language itself is in no small part written in C.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/\" \/>\n<meta property=\"og:site_name\" content=\"IBKR Campus US\" \/>\n<meta property=\"article:published_time\" content=\"2023-12-12T14:12:34+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-15T20:40:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/blue-background-digits-hand.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1000\" \/>\n\t<meta property=\"og:image:height\" content=\"563\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Jonathan Carroll\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Jonathan Carroll\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\n\t    \"@context\": \"https:\\\/\\\/schema.org\",\n\t    \"@graph\": [\n\t        {\n\t            \"@type\": \"NewsArticle\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/#article\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/\"\n\t            },\n\t            \"author\": {\n\t                \"name\": \"Jonathan Carroll\",\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/person\\\/c4fbe8e18075bc8536b7573e2dcb4561\"\n\t            },\n\t            \"headline\": \"Wrapping C Code in an R Package\",\n\t            \"datePublished\": \"2023-12-12T14:12:34+00:00\",\n\t            \"dateModified\": \"2023-12-15T20:40:07+00:00\",\n\t            \"mainEntityOfPage\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/\"\n\t            },\n\t            \"wordCount\": 2458,\n\t            \"commentCount\": 0,\n\t            \"publisher\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/#primaryimage\"\n\t            },\n\t            \"thumbnailUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2023\\\/12\\\/blue-background-digits-hand.jpg\",\n\t            \"keywords\": [\n\t                \"C\",\n\t                \"ChatGPT\",\n\t                \"R\",\n\t                \"Roxygen\",\n\t                \"rstats\"\n\t            ],\n\t            \"articleSection\": [\n\t                \"Data Science\",\n\t                \"Programming Languages\",\n\t                \"Quant\",\n\t                \"Quant Development\",\n\t                \"R Development\"\n\t            ],\n\t            \"inLanguage\": \"en-US\",\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"CommentAction\",\n\t                    \"name\": \"Comment\",\n\t                    \"target\": [\n\t                        \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/#respond\"\n\t                    ]\n\t                }\n\t            ]\n\t        },\n\t        {\n\t            \"@type\": \"WebPage\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/\",\n\t            \"name\": \"Wrapping C Code in an R Package | IBKR Campus US\",\n\t            \"isPartOf\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#website\"\n\t            },\n\t            \"primaryImageOfPage\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/#primaryimage\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/#primaryimage\"\n\t            },\n\t            \"thumbnailUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2023\\\/12\\\/blue-background-digits-hand.jpg\",\n\t            \"datePublished\": \"2023-12-12T14:12:34+00:00\",\n\t            \"dateModified\": \"2023-12-15T20:40:07+00:00\",\n\t            \"inLanguage\": \"en-US\",\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"ReadAction\",\n\t                    \"target\": [\n\t                        \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/\"\n\t                    ]\n\t                }\n\t            ]\n\t        },\n\t        {\n\t            \"@type\": \"ImageObject\",\n\t            \"inLanguage\": \"en-US\",\n\t            \"@id\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/ibkr-quant-news\\\/wrapping-c-code-in-an-r-package\\\/#primaryimage\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2023\\\/12\\\/blue-background-digits-hand.jpg\",\n\t            \"contentUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2023\\\/12\\\/blue-background-digits-hand.jpg\",\n\t            \"width\": 1000,\n\t            \"height\": 563,\n\t            \"caption\": \"Quant\"\n\t        },\n\t        {\n\t            \"@type\": \"WebSite\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#website\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/\",\n\t            \"name\": \"IBKR Campus US\",\n\t            \"description\": \"Financial Education from Interactive Brokers\",\n\t            \"publisher\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\"\n\t            },\n\t            \"potentialAction\": [\n\t                {\n\t                    \"@type\": \"SearchAction\",\n\t                    \"target\": {\n\t                        \"@type\": \"EntryPoint\",\n\t                        \"urlTemplate\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/?s={search_term_string}\"\n\t                    },\n\t                    \"query-input\": {\n\t                        \"@type\": \"PropertyValueSpecification\",\n\t                        \"valueRequired\": true,\n\t                        \"valueName\": \"search_term_string\"\n\t                    }\n\t                }\n\t            ],\n\t            \"inLanguage\": \"en-US\"\n\t        },\n\t        {\n\t            \"@type\": \"Organization\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#organization\",\n\t            \"name\": \"Interactive Brokers\",\n\t            \"alternateName\": \"IBKR\",\n\t            \"url\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/\",\n\t            \"logo\": {\n\t                \"@type\": \"ImageObject\",\n\t                \"inLanguage\": \"en-US\",\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/logo\\\/image\\\/\",\n\t                \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2024\\\/05\\\/ibkr-campus-logo.jpg\",\n\t                \"contentUrl\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/wp-content\\\/uploads\\\/sites\\\/2\\\/2024\\\/05\\\/ibkr-campus-logo.jpg\",\n\t                \"width\": 669,\n\t                \"height\": 669,\n\t                \"caption\": \"Interactive Brokers\"\n\t            },\n\t            \"image\": {\n\t                \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/logo\\\/image\\\/\"\n\t            },\n\t            \"publishingPrinciples\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/about-ibkr-campus\\\/\",\n\t            \"ethicsPolicy\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/cyber-security-notice\\\/\"\n\t        },\n\t        {\n\t            \"@type\": \"Person\",\n\t            \"@id\": \"https:\\\/\\\/ibkrcampus.com\\\/campus\\\/#\\\/schema\\\/person\\\/c4fbe8e18075bc8536b7573e2dcb4561\",\n\t            \"name\": \"Jonathan Carroll\",\n\t            \"url\": \"https:\\\/\\\/www.interactivebrokers.com\\\/campus\\\/author\\\/jonathancarroll\\\/\"\n\t        }\n\t    ]\n\t}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Wrapping C Code in an R Package | IBKR Quant","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.interactivebrokers.com\/campus\/wp-json\/wp\/v2\/posts\/199704\/","og_locale":"en_US","og_type":"article","og_title":"Wrapping C Code in an R Package","og_description":"Those of you who know R really well probably know that the language itself is in no small part written in C.","og_url":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/","og_site_name":"IBKR Campus US","article_published_time":"2023-12-12T14:12:34+00:00","article_modified_time":"2023-12-15T20:40:07+00:00","og_image":[{"width":1000,"height":563,"url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/blue-background-digits-hand.jpg","type":"image\/jpeg"}],"author":"Jonathan Carroll","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Jonathan Carroll","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"NewsArticle","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/#article","isPartOf":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/"},"author":{"name":"Jonathan Carroll","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/person\/c4fbe8e18075bc8536b7573e2dcb4561"},"headline":"Wrapping C Code in an R Package","datePublished":"2023-12-12T14:12:34+00:00","dateModified":"2023-12-15T20:40:07+00:00","mainEntityOfPage":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/"},"wordCount":2458,"commentCount":0,"publisher":{"@id":"https:\/\/ibkrcampus.com\/campus\/#organization"},"image":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/#primaryimage"},"thumbnailUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/blue-background-digits-hand.jpg","keywords":["C","ChatGPT","R","Roxygen","rstats"],"articleSection":["Data Science","Programming Languages","Quant","Quant Development","R Development"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/","url":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/","name":"Wrapping C Code in an R Package | IBKR Campus US","isPartOf":{"@id":"https:\/\/ibkrcampus.com\/campus\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/#primaryimage"},"image":{"@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/#primaryimage"},"thumbnailUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/blue-background-digits-hand.jpg","datePublished":"2023-12-12T14:12:34+00:00","dateModified":"2023-12-15T20:40:07+00:00","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.interactivebrokers.com\/campus\/ibkr-quant-news\/wrapping-c-code-in-an-r-package\/#primaryimage","url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/blue-background-digits-hand.jpg","contentUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/blue-background-digits-hand.jpg","width":1000,"height":563,"caption":"Quant"},{"@type":"WebSite","@id":"https:\/\/ibkrcampus.com\/campus\/#website","url":"https:\/\/ibkrcampus.com\/campus\/","name":"IBKR Campus US","description":"Financial Education from Interactive Brokers","publisher":{"@id":"https:\/\/ibkrcampus.com\/campus\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/ibkrcampus.com\/campus\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/ibkrcampus.com\/campus\/#organization","name":"Interactive Brokers","alternateName":"IBKR","url":"https:\/\/ibkrcampus.com\/campus\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/logo\/image\/","url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2024\/05\/ibkr-campus-logo.jpg","contentUrl":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2024\/05\/ibkr-campus-logo.jpg","width":669,"height":669,"caption":"Interactive Brokers"},"image":{"@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/logo\/image\/"},"publishingPrinciples":"https:\/\/www.interactivebrokers.com\/campus\/about-ibkr-campus\/","ethicsPolicy":"https:\/\/www.interactivebrokers.com\/campus\/cyber-security-notice\/"},{"@type":"Person","@id":"https:\/\/ibkrcampus.com\/campus\/#\/schema\/person\/c4fbe8e18075bc8536b7573e2dcb4561","name":"Jonathan Carroll","url":"https:\/\/www.interactivebrokers.com\/campus\/author\/jonathancarroll\/"}]}},"jetpack_featured_media_url":"https:\/\/www.interactivebrokers.com\/campus\/wp-content\/uploads\/sites\/2\/2023\/12\/blue-background-digits-hand.jpg","_links":{"self":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts\/199704","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/users\/1279"}],"replies":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/comments?post=199704"}],"version-history":[{"count":0,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/posts\/199704\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/media\/199975"}],"wp:attachment":[{"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/media?parent=199704"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/categories?post=199704"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/tags?post=199704"},{"taxonomy":"contributors-categories","embeddable":true,"href":"https:\/\/ibkrcampus.com\/campus\/wp-json\/wp\/v2\/contributors-categories?post=199704"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}