I recently looked into Lua and it seems really nice. The only annoying thing is its lack of (standard) libraries. But with the JIT compiler comes along a nice FFI C interface.
Coming from a java background, i tried to avoid C as much as possible, so my question: has anyone some experience with LuaJIT, especially its FFI interface, and how difficult is it to set up a library for someone with little to no knowledge in C?
Seemed really simple to me, and Mike Pall has some nice tutorials on it here, the lua mailing list also includes some good examples, so check out the archives as well
how difficult is it to set up a library for someone with little to no
knowledge in C?
Really easy. First, you need to declare the functions that you'd like to use. Then, load the target library and assign it to a Lua variable. Use that variable to call the foreign functions.
Here's an example on using function powf from C's math library.
local ffi = require("ffi")
-- Whatever you need to use, have to be declared first
ffi.cdef([[
double powf(double x, double y);
]])
-- Name of library to load, i.e: -lm (math)
local math = ffi.load("m")
-- Call powf
local n, m = 2.5, 3.5
print(math.powf(n, m))
Related
I'm currently playing around with state space models and the book I'm using has some very useful examples.
Problem:
These examples are written in Ox, which somewhat limits its usability, particularly as I want to test out some of my models using the Interactive Brokers API, for which it's more practical to use C# / C++.
More specifically it's using examples from SsfPack which according to this article is "a library of routines for state space
modelling and inference written in C and linked to Ox".
Does this mean it can be directly implemented in C or is it a better approach to write the function in Ox and then call it in C as shown in A1.4 of this document? And if it can be directly implemented, how does one go about it?
Having some experience with C and no experience with Ox, the former of these two options would be much preferable.
Any thoughts welcome!
It seems that there is no official documentation for Ssfpack C routines. Conversely, the ssfpack Ox documentation is well detailed ( see 'SsfPack 3.0: Statistical Algorithms for Models in State Space Form' by Koopman and Doornik ).
If you are an experienced C developer you can observe the ox header file ssfpack.h, you'll find some "extern" declared functions that refers to dll located functions. Those functions can be used in C but you need to find by yourself the prototype of the function. This can be really tricky, maybe impossible, for functions where the number of arguments is not known/not constant.
So, you can call Ssfpack directly from C but, due to the lack of documentation, it is very difficult.
For this reason I would recommend that you write your code in Ox and then call it from C or C#. This require that you learn OX, a good starting point is the book Introduction to Ox by Doornik and Ooms (2006). Then, you need to read the Developer's manual for Ox 7 by Doornik (2012) to understand how to call Ox from C.
I should mention that I'm generating code in C, as opposed to doing this manually. I say this because it doesn't matter too much if there's a lot of code behind it, because the compiler should manage it all. Anyway, how would I go around emulating a lambda in C? I was thinking I could just generate a function with some random name somewhere in the source code and then call that? I'm not too sure. I haven't really tried anything just yet, since I wanted to get the idea down before I implement it.
Is there some kind of preprocessor directive I can do, or some macro that will make this cleaner to do? I've been inspired by Jon Blow to try out compiler development, and he seemed to implement Lambdas in his language Jai. However, I think he does something where he generates bytecode, and then into C? I'm not sure.
Edit:
I'm working on a compiler, the compiler is just a project of mine to keep me busy, plus I wanted to learn more about compilers. I primarily use clang, I'm on Ubuntu 14.10. I don't have any garbage collection, but I wanted to try my hand at some kind of smart pointer-y/rust/ARC inspired memory model for garbage collection, i.e. little to no overhead. I chose C because I wanted to dabble in it more. My project is free software, just a hobby project.
There are several ways of doing it ("having" lambdas in C). The important thing to understand is that lambdas give closures and that closures are mixing "code" with "data" (the closed values); notice that objects are also mixing "code" with "data" and there is a similarity between objects and closures. See also this answer on Programmers.
Traditionally, in C, you not only use function pointers, but you adopt a convention regarding callbacks. This for instance is the case with GTK: every time you pass a function pointer, you also pass some data with it. You can view callbacks (the convention of giving C function pointer with some void*data) as a way to implement closures.
Since you generate C code (which is a wise idea, I'm doing similar things in MELT which -on Linux- generates C++ code at runtime, compile it into a shared object, and dlopen-s that) you could adopt a callback convention and pass some closed values to every function that you generate.
You might also consider closed values as static variables, but this approach is generally unwise.
There have been in the past some lambda.h header library which generates a machine-specific trampoline code for closures (essentially generating a code which pushes some closed values as arguments then call some routine). You might use some JIT compilation techniques (using libjit, GNU lightning, LLVM, asmjit, ....) to do the same. See also libffi to call an arbitrary function (of signature known at runtime only).
Notice that there is a strong -but indirect- relation between closures and garbage collection (read the GC handbook for more), and it is not by accident that every functional language has a GC. C++11 lambda functions are an exception on this (and it is difficult to understand all the intricacies of memory management of C++11 closures). So if you are generating C code, you could and probably should use Boehm's conservative garbage collector (which is wrapping dlopen) and you would have closure GC-ed values. (You could use some other GC libraries, e.g. Ravenbrook's MPS or my unmaintained Qish...) Then you could have the convention that every generated C function takes its closure as first argument.
I would suggest to read Scott's book on Programming Language Pragmatics and (assuming you know a tiny bit of Scheme or Lisp; if you don't you should learn a bit of Scheme and read SICP) Queinnec's book Lisp In Small Pieces (if you happen to read French, read the latest French variant).
In a C program that gets called from within R, I need to use the 'uniroot' function of R. One way to do this is to invoke R again from C with the 'call_R' function. I am wondering if there is a better way ? Is there a function in 'Rmath.h'to do this ?
As per ?uniroot, the R function is basically a wrapper around some freely available C source code for implementing Richard Brent's root finding algorithm -- it even gives the link. So if you're already programming in C, you don't need to touch R at all for this.
The Rmath library provides a number statistical distribution functions, but no access to R itself.
What you want amounts to embedding R in your C program, which is doable but a little tedious. If you are to C++, you could look at my RInside which makes this pretty painless via C++. It comes with a fairly decent number of examples.
I would like to know how to make a C-function and be able to tell Lua about it, then call it from Lua. I have all the Lua Libraries installed on my Mac OSX 10.4 computer.
There's an excellent example of Lua-C integration here and here.
If you just need to export a function into the global namespace, then:
Declare the function (let's call it f) with signature lua_CFunction.
Call lua_register(L, "myfunc", f), with L being the Lua state, and function = f.
Run the lua code. Then f will be available in the global namespace as myfunc.
If you're going to use the stock interpreter then you might want to make a library. This guy wrote an article for Lua Programming Gems that explains how to do it. The sources are available online.
You can register functions using luaL_register
Look at some examples and explanation in PiL
My answer here includes a nice, short example about making a very simple game using C and Lua together. In my biased opinion, it's a great starting point.
At the risk of oversimplifying something I'm worried might be ridiculously complex, what should I be aware of when mixing C and Objective-C?
Edit: Just to clarify, I've never worked with C before, and I'm learning Objective-C through Cocoa. Also I'm using the Chipmunk Dynamics engine, which is C.
I'd put it the other way around: you might be risking overcomplicating something that is ridiculously simple :-)
Ok, I'm being a bit glib. As others are pointing out, Objective-C is really just a minimal set of language extensions to C. When you are writing Objective-C code, you are actually writing C. You can even access the internal machinations of the Objective-C runtime support using some handy C functions that are part of the language (no... I don't recommend you actually DO this unless you really know what you're doing).
About the only time I've ever had mildly tricky moments is when I wanted to pass an Objective-C instance method as a callback to a C function. Say, for example, I'm using a pure-C cross platform library that has functions which accept a callback. I might call the function from within an object instance to process some data, and then want that C function to call my instance BACK when its done, or as part of getting additional input etc etc (a common paradigm in C). This can be done with funky function wrapping, and some other creative methods I've seen, and if you ever need to do it googling "objective-c method for c callback" or something like that will give you the goods.
The only other word of advice is to make sure your objects appropriately manage any manually malloced memory that they create for use by C functions. You'll want your objective-c classes to tidy up that memory on dealloc if, indeed, it is finished.
Other than that, dust off any reference on C and have fun!
You can't 'mix' C and Objective-C: Objective-C is a superset of C.
Now, C++ and Objective-C on the other hand...
Objective C is a superset of C, so it shouldn't conflict.
Except that, as pointed here pure C has different conventions (obviously, since there is no built-in mechanism) to handle OO programming. In C, an object is simply a (struct *) with function pointers.