c++ And lua-how to begin? - c++

im trying out other languages.
Got VB2013 and LuaForWindows 5.1 What is the most basic file structure to run a .lua file in my program??
I have currently done http://www.youtube.com/watch?v=w51pftzS1_8 includes part, made a .h file that looks like this
#ifndef __LUA_INC_H__
#define __LUA_INC_H__
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#endif // __LUA_INC_H__
and a Run.cpp like this
#include <iostream>
#include <conio.h>
#include <iostream>
#include "LuaInc.h"
using namespace std;
int main()
{
int iErr = 0;
lua_State *lua = lua_open(); // Open Lua
luaopen_io(lua); // Load io library
if ((iErr = luaL_loadfile(lua, "test.lua")) == 0)
{
// Call main...
if ((iErr = lua_pcall(lua, 0, LUA_MULTRET, 0)) == 0)
{
// Push the function name onto the stack
lua_pushstring(lua, "helloWorld");
// Function is located in the Global Table
lua_gettable(lua, LUA_GLOBALSINDEX);
lua_pcall(lua, 0, 0, 0);
}
}
lua_close(lua);
_getch();
return 0;
}
the test.lua file is in the vb213 projects dir/MYPROJECT/MYPROJECT
and looks like this
function helloWorld ()
io.write ("hello World")
end

From VS2013 and Lua for Windows, you are going to have some pain related to getting the right C Runtime Library version in play. Lua for Windows was compiled against an older version of the CRT, that came with VS2005. It may or may not be possible to get VS2013 to link against that older version. Mixing CRT versions is a recipe for much confusion.
The easiest way out is to get a version of the Lua core built for your version of Visual Studio. There are two ways to do that.
Download a version from Lua Binaries. There are pre-built versions of Lua available from the "official" Lua Binaries distribution. It can be had for 32-bit and 64-bit builds, for Windows, and for other platforms.
Build Lua yourself as part of your solution. Building your own Lua51.dll is straightforward, the default configuration is sensible. It mostly amounts to including almost all the .c files in a DLL project. Note that lua.c is not part of the DLL, that is the source to lua.exe. Similarly, luac.c is not part of the DLL, it is the source to luac.exe which does require some care to build yourself; but you aren't likely to need it.
Either way, you need to pay attention to some details.
The Lua API is a C API, not C++. So if you insist on making your application be a C++ application, you should wrap the inclusion of the Lua header files inside of an exern "C" block:
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
In principle, you can build the Lua core as C++ instead. The core is written in a clean C flavor that is also a subset of C++, and is tested when compiled as C++. However, if you go that route then you must build any binary modules yourself against your C++ linkage, and that way can lie madness if you depend on many community supplied modules.
I believe that all of the builds available at Lua Binaries are compiled as C, not C++, so the extern "C" declaration will be required with those.

Well, for starters, I would recommend scratching c++ and switching to lua as your primary programming language. It is quite messy to call lua functions from with c++, at least that is my experience. Once you understand enough of Lua, THEN call c/c++ functions from Lua via dll or other file/system formats. I was torn between learning python or c/c++ and I chose python. From there I learned about Lua and loved it more than python. Again this is just my experience and suggestion. Now to answer your question, why run Lua in C++? Lua is based on the C API, so I would just use raw C or just stick with C++. I say this only because Lua is technically no different than a watered down version of C. However, Lua is not "watered down" any more, as it can be used as a fully operational standalone programming language.

Related

How do is structure my files right, when I write code for linux and windows

I am currently not sure how I should seperate my code best. I currently programming a software which should run on Linux and Windows. So I decided to put all OS-secificstuff in thier own folder/files.
For example
This is the header file:
#ifdef __linux__
#include <unistd.h>
#elif _WIN64
#include <Windows.h>
#endif
#include <string>
#include <iostream>
#pragma once
class SystemTools
{
public:
// Delay in secounds until the programm continues
static void sleep(int delay);
private:
};
and the OS specific implementation is in the linux/windows folder
Linux:
#ifdef __linux__
#include "../SystemTools.h"
void SystemTools::sleep(int delay)
{
usleep(delay*1000000);
}
#endif
Windows:
#ifdef _WIN64
#include "../SystemTools.h"
void SystemTools::sleep(int delay)
{
Sleep(delay*1000);
}
#endif
This works and I have no problems so far, but when I now have methods which don´t need any OS specific code I created an additional folder "Generic" so I can write the code in there and don´t have to mantain the same code in the linux and windows file. For example like that:
Generic:
#include "../SystemTools.h"
void SystemTools::sleepMin(int delay)
{
sleep(delay*60);
}
#endif
That still workes on Linux but not on Windows (no error but does not compile, used codeblockes for that on windows). So how do I organize my code correct? Should I use only one file with ifdef even it that gets very fast ugly?
(compiler Linux: g++, Windows: should be MinGW)
Firstly I'd suggest you to use the most recent of C++ (C++20 or so) on your project. This way, we can abstract many OS related calls (like threading, synchronization, random numbers and etc).
That means, you won't really need to use too many of OS specific APIs. IE: C++11 and earlier already have a standard way to sleep:
https://en.cppreference.com/w/cpp/thread/sleep_for
In the end, if you really need to call OS specific things on windows and on linux, using a library could be interesting and pay attention that windows C++ compiler (visual studio) really like to use 'pre compiled headers' so, it's interesting to have a single header file where all windows specific headers can be included.
Basically that. You can have a standard Cmake or makefile for your linux build and use .sln Visual Studio project to build it to windows.
That's the way I would do that

Use NetCDF4-C in Unity

this is my first time posting (after lurking for years).
A project I will be tackling is to use NetCDF4 (.nc) files in Unity on Windows. I will be using Unity 5.4.0f3 and Windows 10, and I have developed in Unity before and am familiar with C# and JavaScript, but NetCDF only has C, Java, and Fortran APIs, although there are wrappers in Python, C++, and others (source: https://www.unidata.ucar.edu/publications/factsheets/current/factsheet_netcdf.pdf).
So my specific question is how do I call NetCDF4-C functions (nc_get_vara_float(), nc_open, etc) in C# for use in Unity?
What I've tried so far:
To start, I googled specifically for NetCDF4-C + Unity tutorials/attempts, but did not find anything, so instead I have been looking into the compatibility of calling C functions from C#. I am currently working on a project on Linux with NetCDF4-C and written custom wrapper functions for the netcdf.h functions, so I was hoping I could reuse my code there.
I attempted to follow this SO post (Is it possible to call a C function from C#.Net) but get an error in Unity when trying to Play: "DllNotFoundException: test.so" (my file was named "test.c"). From the comments, it seems Linux uses .so files but Windows uses .dll, and I was not sure how to generate a .dll of a C file.
I looked up another post on that (How to write a DLL file in C?) and downloaded Visual Studio to follow along. While VS was downloading, I looked up how to use GCC to compile (Creating a DLL in GCC or Cygwin?), and used the Bash subsystem ("Bash on Ubuntu on Windows" terminal) but got a handful of errors that indicated the code from the previous link (2nd SO link in this post) were for C++, so I stopped working with GCC.
Once VS finished installing, I went back to trying to use VS to create the .dll, and attempted to combine the solutions from both SO posts (1 and 2) so that I would be able to use the .dll file containing C code in Unity, but to no avail: I get the same error but just with a different extension (and different name on purpose): "DllNotFoundException: Win32Project1.dll".
The code I have is as follows:
test.cs (used in Unity and attaches to a Component):
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class test : MonoBehaviour {
[DllImport("Win32Project1.dll", EntryPoint="DisplayHelloFromMyDLL")]
public static extern void DisplayHelloFromMyDLL ();
// Use this for initialization
void Start () {
DisplayHelloFromMyDLL();
}
// Update is called once per frame
void Update () {
}
}
Win32Project1.dll (created and built in Visual Studio):
#include <stdio.h>
extern "C"
{
__declspec(dllexport) void DisplayHelloFromMyDLL()
{
printf("Hello DLL.\n");
}
}

Accessing static members of a class from dll

I have application written in C++ that uses SWIG for python integration.
Now under linux/osx when i build swig wrapper it creates so file that is used from application like this.
Py_Initialize();
PyRun_SimpleString("import MoBridge");
PyRun_SimpleString("a = MoBridge.MoBridge()");
PyRun_SimpleString("a.CreateQuadMesh()");
Py_Finalize();
What this does is it imports wrapper MoBridge, then it calls trough wrapper C++ function CreateQuadMesh(). Wrapper roughly looks roughly like this
h file:
#include "MoEngine.h"
class MoBridge
{
public:
MoBridge();
~MoBridge();
void CreateQuadMesh();
};
cpp file:
#include "mobridge.h"
void MoBridge::CreateQuadMesh()
{
MoEngine::CreateMesh();
}
The wrapper calls MoEngine static function and it in turn does what it does.
Now this works great under Linux/osx if I understood it correctly because the way so file is linked.
But under windows I had to create DLL and as far as I found DLL files are loaded differently so they live in different memory from the rest of the application and hence cannot see applications other static methods.
I know that I can use dllexport to expose methods from dll to the rest of the application. But in this case I'm looking on how to allow dll to access rest of the applications static functions in applications memory.
I would appreciate any point in the right direction.
If anyone gets stuck with this I have found solution that will resolve this in both linux, osx and windows.
using shared object *.so will of course work with linux/osx but luckily there is even easier solution to use with SWIG that is really not documented in SWIG but it's documented in python documentation (thank you python!)
For this to work you don't need to create dll or so file from your wrapper but after swig creates your *_wrap.cxx file you should include it in your project and before calling Py_Initialize() you import your module like this.
PyImport_AppendInittab("_MoBridge", PyInit__MoBridge);
Then you can use as previously mentioned:
Py_Initialize();
PyRun_SimpleString("import MoBridge");
PyRun_SimpleString("a = MoBridge.MoBridge()");
PyRun_SimpleString("a.CreateQuadMesh()");
Py_Finalize();
And basically since you have your *_wrap.cxx in your project and python is essentially living within your application since you initialised it you have exactly same behaviour like if you have used so in linux/osx except this work on all three platforms.
Cheers!

How to use a C struct in C++ code?

I am trying to write a program that should use a C library (the LIS library) in a C++ program. There seems to be a problem with the creation/initialization of struct objects.
When I run the example program on the wikipediapage: http://en.wikipedia.org/wiki/Lis_%28linear_algebra_library%29 it runs like a charm, but of course that is compiled as a C program.
In my C++ code I do it as follows:
#include "stdafx.h"
#include <iostream>
extern "C"
{
#include "lis.h"
#include "lis_config.h"
LIS_MATRIX A;
}
using namespace std;
int main(LIS_INT argc, char* argv[])
{
lis_initialize(&argc, &argv);
lis_matrix_create(LIS_COMM_WORLD, &A);
getchar();
return 0;
}
When I run this code, it gives me an access violation at the line lis_matrix_create. It seems as though A has an memory address, its data members (LIS_MATRIX is defined as a struct in Lis.h) have not been initialized, and therefore their addresses are NULL.
Could you please tell me how to create the LIS_MATRIX in such a way that I can use it like it is done in the example code on the wikipedia page?
Thank you in advance!
In reply to Adam and Ross Ridge:
I use visual studio 2013 on Windows 7 64 bit. The manual of the Lis library states that it is compatible with the Visual Studio 2008, 2010 and 2012 compilers, and also with gcc 3.4 and 4.4 and some IBM, Intel and PGI C++ compilers, I hope Visual Studio 2013 will not be a problem.
Also, in this code, if I take out the 'extern C' block, and include 'stdio.h' instead of iostream, it runs without problems (so I guess that it means the C compiler is used?). The minute I also include iostream, the access violation start.
You are including
lis_config.h
after
lis.h
wich is per se an error(you have to include it before). Also if you touched anything in lis_config you have to rebuild the whole library (using most same compilers flag of your project, for example "-msee2" if you used SSE2). Before rebuilding just swap headers only to see if that is enough..
A few more words: a library can easily detect headers included in wrong order, make a ticket to lis developers for that.

Visual studio C++: How to make parts of code not be seen by the windows compiler?

So jenerally I have small C++ project based on OpenSource crossplatform libs. So it probably would compile under linux. So I hited the point when I need to implement some defenatly platform specific class functions.
I have a class header with all functions declarations and cpp file with realisations. So first: how to declare my platform specific functions in header so when I'll try to compile under linux it will not try to compile windows specific ones... and when on windows compiler will not try to compile linux functions include headers etc.
So for windows I need some how wrap such super specific functions
HRESULT EnumerateDevices(REFGUID category, IEnumMoniker **ppEnum)
void DisplayDeviceInformation(IEnumMoniker *pEnum)
And some headers
#include <windows.h>
#include <dshow.h>
#pragma comment(lib, "strmiids")
While for linux I have such headers
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/videodev.h>
And I have function with name of void PrintCamerasList() which I wanna have one for bouth platfrms realisations for which I have seprate.
I hope you see what I need. So generally I need some example using my functions or once you can invent - let your imagination flow!)
So why do I need it all - I am creating some console app using OpenCV and I need to list user cameras names. OpenCV cannot do this on its own. so I asked how to do it for bouth platforms of my intrest - windows and linux
You want to look into platform specific macros and surround for example your MSVC specific code with some #ifdef _WIN32 / #endif pairs.
Take a look at http://predef.sourceforge.net/ for an extensive list of pre-defined macros various compilers provide to distinguish between operating systems, compilers, and processor architectures. They will allow you to distinguish between more than just Win32 and Linux if necessary.
Common practice is to use a compiler flag such as
#ifdef WIN_32
// Windows stuff...
#else
// Linux stuff
#endif
Check for the exact values of what windows flag is defined either in your compiler or in the headers you include