I am working on a 2D game engine at the moment and have hit a stumbling block whilst implementing the LUA scripting / Interpreter.
I'm using SWIG and have got the basics all working fine.
In the engine I use the GLM (OpenGL Mathematics Libary http://glm.g-truc.net/) for all Vector and Matrix related areas.
I really need to expose glm (at a basic level) to the via SWIG to LUA so I can call methods in LUA like:
actor:GetPosition() <- Which returns a glm::vec2
GLM is quite a complex library (possibly an understatement lol) and I do not require the whole thing exposed, that would be ridiculous amounts of work I assume. I simply want to be able to access the xy components of the glm::vec2 class.
I'm sure this must be easy as SWIG doesn't require a full class definition and there must be a way to let SWIG just assume that the glm::vec2 class just has x,y params.
I'm not sure If using Proxy classes in SWIG is the way to do this ? or some other method ? I'm quite new to LUA integration and SWIG also.
One route I really don't want to go down is ditching GLM and writing my own Vector/Matrix library which is much more simple, no templates etc and I can then simply wrap with SWIG, but I feel this would be a waste of time and I would ultimately end up with a less powerful Math Library :(.
Thanks in advance and I can provide more info if necessary.
The big problem with GLM is that its vector types use things that have dubious C++ validity. Things that many compilers will allow, but are not allowed by the standard. SWIG uses its own parser to work, so it's going to have a hard time making heads or tails of GLM's definitions.
In a case like this, I would suggest using something like Luabind rather than SWIG. It gives a bit more fine-grained control in such circumstances, and it has the benefit of not using its own parser. Granted, you could effectively rewrite the prototypes for the important parts of GLM in your .swig file.
A solution in luabind would look like this:
#include <luabind/luabind.hpp>
extern "C" int init(lua_State* L)
{
using namespace luabind;
using namespace glm;
open(L);
module(L)
[
class_<dvec2>("dvec2")
.def_readwrite("x", &dvec2::x)
.def_readwrite("y", &dvec2::y)
];
return 0;
}
Related
I have multiplatform game written in C++. In the mac version, even though I do not have any obj-c code, one of the libraries I use seems to be auto-releasing stuff, and I get memory leaks for that, since I did not create a NSAutoreleasePool.
What I want is to be able to create (and destroy) a NSAutoreleasePool without using obj-c code, so I don't need to create a .m file, and change my build scripts just for that. Is that possible? How can that be done?
OBS: Tagged C and C++, because a solution in any of those languages will do.
You can't avoid instantiating the Objective-C runtime—but apparently you've already got one of those.
If you want to interact with the runtime from C, you can us the Objective-C runtime APIs, as documented in Objective-C Runtime Programming Guide and Objective-C Runtime Reference.
The idea is something like this (untested):
#include <objc/runtime.h>
#include <objc/objc-runtime.h>
id allocAndInitAutoreleasePool() {
Class NSAutoreleasePoolClass = objc_getClass("NSAutoreleasePool");
id pool = class_createInstance(NSAutoreleasePoolClass, 0);
return objc_msgSend(pool, "init");
}
void drainAutoreleasePool(id pool) {
(void)objc_msgSend(pool, "drain");
}
If you want to call these functions from another file, of course you'll have to include objc/runtime.h there as well. Or, alternatively, you can cast the id to void* in the return from the allocAndInit function, and take a void* and cast back to id in the drain function. (You could also forward-declare struct objc_object and typedef struct objc_object *id, but I believe that's not actually guaranteed to be the right definition.)
You shouldn't have to pass -lobjc in your link command.
Needless to say, it's probably less work to just make your build scripts handle .m files.
Sorry if this question has been asked before. I'm really not sure how to search for it.
What I'm trying to do is build up a library of functions for myself to make life easier in my future school work. I built up a set of functions that handle Geometry based things, like 3D vectors and points and planes along with all of their associated methods (dot, cross, scale).
Through some googling, I found the Eigen library which implements everything I want, including alot of SSE stuff to make it fast.
I don't understand SSE and alot of the stuff they did in that library, so I don't want to use it as my development library. What I mean by that is, I want to code everything using my dumb, slow versions that I know how they work so I can make sure I'm doing everything right. Then once I'm sure the math is coming out right, I'd like to switch it over to using the Eigen library for efficiency.
Is there some way to make it so I can set a flag, or pass a variable, (maybe some template thing?) so that I can switch my code from my stuff to the Eigen stuff without having to rewrite my applications?
Basically I'd like to make a standard interface between the two libraries.
The Eigen library code would be included in the same directory. I'd have my Geometry.h, and then a Eigen folder that contains all of that library.
I don't know how to bridge the gap between the two. Would I need to write wrapper methods for all of their stuff so it has a common API?
EDIT ::
I should also add that I'd like this to be as fast as possible. For things like dot, cross, and matrix functions that could get called many times, I'd like to not have to go through virtual functions or too complex of wrapper methods that could negatively impact performance.
Am I asking too much?
END EDIT
Something like this is what I want in effect. But I'm pretty sure this doesn't do what I want.
#ifdef BASIC_LIBRARY
class Vector3
{
float x,y,z;
float dot(Vector3);
}
#endif
#ifdef EIGEN_LIBRARY
//some sort of passthrough to eigen library
#endif
I'd suggest using namespaces for this:
namespace geometry {
class Vector3 {
...
};
}
namespace eigen {
using geometry::Vector3;
...
}
Basically this would allow you to define your basic geometry types & operations, and then use selected portions directly from within the other namespace.
I've been looking for a language that provides the same functionality that Coffeescript has, but for C/C++. I mean a language that converts the code into C, but readable, just like CoffeeScript converts to Javascript, readable and all.
I think this is possible, and even desirable (I grudgingly deal with C++ when writing Node.js native modules), but more challenging than with a higher-level language like JavaScript.
What you're asking for is a language that would provide syntactic sugar without sacrificing performance or flexibility. Some syntactic sugars (say, syntactic whitespace or Ruby-style def/end blocks instead of curly braces) would be trivial to add. But adding anything more advanced, you'd run into two major hurdles: static typing, and garbage collection.
For instance, let's say that you wanted to add implicit returns. It seems like a small feature, but think about it: In order for the feature to be useful, you'd have to—at the very least—throw a compile-time error when the value of the last expression doesn't match the function's return type. That means that your compiler needs to inspect a line like
a->b
and figure out what type it is. That's possible in principle, but it's a heck of a lot more work than the CoffeeScript compiler does.
Or say you added list comprehensions. That means you're allocating an array whose length isn't known at compile-time, which means you'll need to later deallocate it yourself. So the syntactic sugar could actually hurt you. The rule "If you malloc it, you free it" doesn't work if the compiler is adding in the malloc for you, unless it can figure out where to put the free (which, again, is generally possible but would take a lot of work).
So, while I'd love to someone give C++ the CoffeeScript treatment, I don't expect it to happen any time soon—if ever. I think it's more likely that the world will eventually move on to something like D or Go for system-level programming.
I think OOC is probably the closest thing to Coffeescript for C. It's a programming language with a lot of the features you'd expect from dynamic languages (objects, first class functions, clean syntax) that compiles directly into C99.
http://ooc-lang.org/
One item missing from Jacindas list you might want to know about: Vala/Genie is a compiler targetting C with the GObject library implementing objects, written by Gnome. Vala is a C#-like syntax, and Genie a Python-like syntax, but for the rest they are the same system. It was actually created because bare C + GObject became too much of a pain to work with for the Gnome guys. Vala does objects and automatic memory management based on reference counting or ownership tracking, and a lot of other things you'd expect in a C# like language.
As for the CoffeeScript-like property, I just saw that there was an experimental feature to disable the dependency of the generated code on GObject, so it generates just plain C without any runtime dependencies. Doing so disables a number of more advanced OO features, but it still leaves you with a better syntax, a basic object system, and (semi-)automatic memory management.
I don't know how readable the output is, but if you run it through a pretty printer it might be very close to what you're looking for.
SugarCpp is a language which can compile to C++11. It should be what you are looking for. Visit https://github.com/curimit/SugarCpp for more details.
For Python specifically, take a look at this question:
Convert Python program to C/C++ code?
They mention Shed Skin, which will take a subset of pure python and convert to standalone C++ code.
Cython is typically used to create Python extension modules, but can create standalone programs if the Python interpreter is embedded. This doesn't sound like what you're looking for, though.
Cython is based on Pyrex, and they are compatible with each other in many ways.
For some of the other languages you mentioned there seem to be similar projects: Ruby and PHP. Toba for Java (though no longer maintained), Marst for Algol, BCX for BASIC, COB2C, PtoC for Pascal and I should probably stop there before this turns into "List of Converters from Foo to C/C++."
Hope that helps!
Take a look at this fresh new project: https://bixense.com/coffeepp/
Coffee++
Coffee++ is a little language that compiles into C++. It has been created to have something similar to CoffeeScript for C++. Currently Coffee++ is in a alpha state and not at all usable or final. Check out the source on Github to get involved.
The golden rule of Coffee++ is: "It's just C++". The code compiles one-to-one into the equivalent C++, and there is no runtime library. You can use any existing C++ library seamlessly from Coffee++ (and vice-versa).
Overview:
source file Test.cf++
include iostream
int main():
age := 5
dog := Dog(age)
if age != 7:
dog.bark()
class Dog:
public Dog(int age):
this->age := age
public void bark():
std::cout << "Woof!\n"
private int age
};
compiled Test.hpp
#pragma once
int main();
class Dog {
public:
Dog();
void bark();
private:
int age;
};
compiled Test.cpp
#include "test.hpp"
#include <iostream>
int main() {
auto age = 5;
auto dog = Dog(age);
if (age != 7) {
dog.bark();
}
}
Dog::Dog(int age) : age(age) {
}
void Dog::bark() {
std::cout << "Woof!\n";
}
Since vala and genie were already mentioned, I'll put BaCon (Basic Converter) out there for those who reminisce about hand coding programs from a monthly print publication, but want to use it with a modern GUI.
Must run on each Unix/Linux/BSD platform, including MacOSX
Converted sourcecode must be compilable with GCC
Must resemble genuine BASIC with implicit variable delarations
Spoken language constructs are preferred
The website http://www.basic-converter.org/ has lots of examples (some of theme pretty complex for "BASIC") and plugins for nearly every opensource IDE or you can use the BACON IDE.
Well, this is not what you want, but.. : http://www.campbell.nu/oscar/cython/index.html - This cython/cytoc is a significant space (pythonish) transpiler for C/C++ that I coded around 1999/2000, it has no relation to the cython project that arrived seven years later.
Frankly, I wrote it in Perl and it's heuristical, using regular expressions. I used it for an entire project of a Gameboy Color game (regular ansi C). But I wouldn't trust it... Which is why I'm looking around too, instead of using that dusty old bugger ;)
Follow up:
I've been working on Onyx (https://github.com/ozra/onyx-lang) for a year plus now, and finally realized the obvious thing to do is rewrite it to compile to C++ instead of LLVM-IR. The re-target idea is brand fresh, so rewrite is still vapor. But your input would be made well use of in RFC's, if you like the idea of the language, it's your chance to shape it.
is it possible to wrap a c++ library into c?
how could i do this?
are there any existing tools?
(need to get access to a existing c++ library but only with C)
You can write object-oriented code in C, so if it's an object-oriented C++ library, it's possible to wrap it in a C interface. However, doing so can be very tedious, especially if you need to support inheritance, virtual functions and such stuff.
If the C++ library employs Generic Programming (templates), it might get really hairy (you'd need to provide all needed instances of a template) and quickly approaches the point where it's just not worth doing it.
Assuming it's OO, here's a basic sketch of how you can do OO in C:
C++ class:
class cpp {
public:
cpp(int i);
void f();
};
C interface:
#ifdef __cplusplus
extern "C" {
#endif
typedef void* c_handle;
c_handle c_create(int i)
{
return new cpp(i);
}
void c_f(c_handle hdl)
{
static_cast<cpp*>(hdl)->f();
}
void c_destroy(c_handle hdl)
{
delete static_cast<cpp*>(hdl);
}
#ifdef __cplusplus
}
#endif
Depending on your requirements, you could amend that. For example, if this is going to be a public C interface to a private C++ API, handing out real pointers as handles might make it vulnerable. In that case you would hand out handles that are, essentially, integers, store the pointers in a handle-to-pointer map, and replace the cast by a lookup.
Having functions returning strings and other dynamically sized resources can also become quite elaborate. You would need the C caller provide the buffer, but it can't know the size before-hand. Some APIs (like parts of the WIn32 API) then allow the caller to call such a function with a buffer of the length 0, in which case they return the length of the buffer required. Doing so, however, can make calling through the API horribly inefficient. (If you only know the length of the required buffer after the algorithm executed, it needs to be executed twice.)
One thing I've done in the past is to hand out handles (similar to the handle in the above code) to internally stored strings and provide an API to ask for the required buffer size, retrieve the string providing the buffer, and destroy the handle (which deletes the internally stored string).
That's a real PITA to use, but such is C.
Write a c++ wrapper that does an extern c, compile that with c++, and call your wrapper.
(don't “extern c”)
extern C only helps you to have a names in dll like you see them.
You can use
dumpbin /EXPORTS your.dll
to see what happens with names with extern C or without it.
http://msdn.microsoft.com/en-us/library/c1h23y6c(v=vs.71).aspx
To answer your question... It depends... But it is highly unlikely that you can use it without wrappings. If this C++ library uses just a simple functions and types you can just use it. If this C++ library uses a complex classes structure - probably you will be unable to use it from C without wrapping. It is because the internal of classes may be structured one way or another depending on many conditions (using inference with virtual tables or abstracting. Or in example complex C++ library may have its own object creation mechanisms so you HAVE to use it in the way it is designed or you will get unpredictable behavior).
So, I think, you have to prepare yourself for doing dome wrappings.
And here is a good article about wrapping C++ classes. It the article the Author tells about wrapping C++ classes to C# but he uses C at first step.
http://www.codeproject.com/KB/cs/marshalCPPclass.aspx
If the C++ library is written which can be compiled with C compiler with slight editting (such as changing bool to int, false to 0 and true to 1 etc), then that can be done.
But not all C++ code can be wrapped in C. Template is one feature in C++ that cannot be wrapped, or its nearly impossible.
Wrap it in C++ cpp that calls that dll, and "extern C" in that file you made.
I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is:
What is the simplest way to release GIL for these method calls?
(I understand that if I used a C library I could wrap this with some additional C code, but here I use C++ and classes)
Not having any idea what SWIG is I'll attempt an answer anyway :)
Use something like this to release/acquire the GIL:
class GILReleaser {
GILReleaser() : save(PyEval_SaveThread()) {}
~GILReleaser() {
PyEval_RestoreThread(save);
}
PyThreadState* save;
};
And in the code-block of your choosing, utilize RAII to release/acquire GIL:
{
GILReleaser releaser;
// ... Do stuff ...
}
The real problem is that SWIG is not documented well (I saw hints to use changelog for searching ;) ).
Ok, I found out that I can do inline functions in SWIG and use macros to release/acquire GIL, it looks like this:
%inline %{
void wrappedFunction(OriginalObject *o, <parameters>) {
Py_BEGIN_ALLOW_THREADS
o->originalFunction(<parameters>);
Py_END_ALLOW_THREADS
}
%}
This function is not present in original C++, but available in python module. This is (almost) exactly what I wanted. (what I would like is to wrap original method like python decorator does)
You can use the same API call as for C. No difference. Include "python.h" and call the appoproate function.
Also, see if SWIG doesn't have a typemap or something to indicate that the GIL shuold not be held for a specific function.