Initiate Code in Emacs - code-snippets

I use emacs to mostly code in c++. Is there any way to add a particular piece of code snippet to every new file opoened in Emacs.
For eg:
Suppose i want to create a new file in emacs with name abc.cpp and emacs by default initiates the file with following lines
using namespace std;
int main(){
return 0;
}

Like this:
(defun insert-my-c++-headers ()
(when (= 0 (buffer-size))
(insert "using namespace std;\n\nint main(){\n return 0;\n}\n")))
(add-hook 'c++-mode-hook 'insert-my-c++-headers)

Related

How to change import module name "env" in wasm?

In a wasm source code, when an undefined function is used, the compile will add this function into module named "env".
I want to change the name "env" to another like "myenv"
#include <stdio.h>
extern int butt();
int main()
{
butt();
printf("123\n");
}
the wast file looks like this
(import "env" "butt" (func $butt (result i32)))
How to change my c-code so that the "butt" is under "myenv".
That's what I expect for.
(import "myenv" "butt" (func $butt (result i32)))
I'm using clang compiler to generate wasm file.
Currently there is no way to change the default, but for a given symbol you can use the import_name attribute:
https://clang.llvm.org/docs/AttributeReference.html#import-module

How to get a field's type by using CDT parser

I'm trying to extract c++ source code's info.
One is field's type.
when source code like under I want to extract info's Type when info.call() is called.
Info info;
//skip
info.call(); //<- from here
Trough making a visitor which visit IASTName node, I tried to extract type info like under.
public class CDTVisitor extends ASTVisitor {
public CDTVisitor(boolean visitNodes) {
super(true);
}
public int visit(IASTName node){
if(node.resolveBinding().getName().toString().equals("info"))
System.out.println(((IField)node.getBinding()).getType());
// this not work properly.
//result is "org.eclipse.cdt.internal.core.dom.parser.ProblemType#86be70a"
return 3;
}
}
Assuming the code is in fact valid, a variable's type resolving to a ProblemType is an indication of a configuration problem in whatever tool or plugin is running this code, or in the project/workspace containing the code on which it is run.
In this case, the type of the variable info is Info, which is presumably a class or structure type, or a typedef. To resolve it correctly, CDT needs to be able to see the declaration of this type.
If this type is not declared in the same file that's being analyzed, but rather in a header file included by that file, CDT needs to use the project's index to find the declaration. That means:
The AST must be index-based. For example, if using ITranslationUnit.getAST to create the AST, the overload that takes an IIndex parameter must be used, and a non-null argument must be provided for it.
Since an IIndex is associated with a CDT project, the code being analyzed needs to be part of a CDT project, and the project needs to be indexed.
In order for the indexer to resolve #include directives correctly, the project's include paths need to be configured correctly, so that the indexer can actually find the right header files to parse.
Any one of these not being the case can lead to a type resolving to a ProblemType.
Self response.
The reason I couldn't get a binding object was the type of AST.
When try to parse C++ source code, I should have used ICPPASTTranslationUnit.
There is no code related this, I used IASTTranslationUnit as a return type of AST.
After using ICPPASTTranslationUnit instead of IASTTranslationUnit, I solved this problem.
Yes, I figure it out! Here is the entire code which can index all files in "src" folder of a cpp project and output the resolved type binding for all code expressions including the return value of low level API such as memcpy. Note that the project variable in following code is created by programatically importing an existing manually configured cpp project. I often manually create an empty cpp project and programatically import it as a general project (once imported, Eclipse will automatically detect the project type and complete the relevant configuration of CPP project). This is much more convenient than creating and configuring a cpp project from scratch programmatically. When importing project, you'd better not to copy the project or containment structures into workspace, because this may lead to infinitely copying same project in subfolder (infinite folder depth). The code works in Eclipse-2021-12 version. I download Eclipse-For-cpp and install plugin-development and jdt plugins. Then I create an Eclipse plugin project and extend the "org.eclipse.core.runtime.applications" extension point.
In another word, it is an Eclipse-Application plugin project which can use nearly all features of Eclipse but do not start the graphical interface (UI) of Eclipse. You should add all cdt related non-ui plugins as the dependencies because new version of Eclipse does not automatically add missing plugins any more.
ICProject cproject = CoreModel.getDefault().getCModel().getCProject(project.getName());
// this code creates index for entire project.
IIndex index = CCorePlugin.getIndexManager().getIndex(cproject);
IFolder folder = project.getFolder("src");
IResource[] rcs = folder.members();
// iterate all source files in src folder and visit all expressions to print the resolved type binding.
for (IResource rc : rcs) {
if (rc instanceof IFile) {
IFile f = (IFile) rc;
ITranslationUnit tu= (ITranslationUnit) CoreModel.getDefault().create(f);
index.acquireReadLock(); // we need a read-lock on the index
ICPPASTTranslationUnit ast = null;
try {
ast = (ICPPASTTranslationUnit) tu.getAST(index, ITranslationUnit.AST_SKIP_INDEXED_HEADERS);
} finally {
index.releaseReadLock();
}
if (ast != null) {
ast.accept(new ASTVisitor() {
#Override
public int visit(IASTExpression expression) {
// get the resolved type binding of expression.
IType etp = expression.getExpressionType();
System.out.println("IASTExpression type:" + etp + "#expr_str:" + expression.toString());
return super.visit(expression);
}
});
}
}
}

lua require function does not find my required file on iOS

I'm new to lua, this might be something quite simple, but I couldn't figure it out. I did all night search, read some posts here, but are not quite what I'm looking for. I finally worked out a lame solution that i'm not happy with, so I'm here to ask for help.
I'm trying to embed lua inside c++, and this program will run as part of an app on the iPhone, as we know, every iPhone app has a resource bundle, and the lua scripts are distributed with the bundle.
// I printed out the bundle path:
bundle directory /var/mobile/Applications/C6CEF090-B99A-4B9B-ADAC-F0BEF46B6EA4/LuaThirdTry.app
Say I have two script files (main.lua, mylib.lua) in the same folder, I put them in my Xcode project, organized like this:
somefolder
|--main.lua
|--mylib.lua
and main.lua is as below:
--main.lua
print(package.path)
require("mylib")
obviously I want to use code from mylib.lua, however, I got error from lua vm:
/usr/local/share/lua/5.2/?.lua;/usr/local/share/lua/5.2/?/init.lua;/usr/local/lib/lua/5.2/?.lua;/usr/local/lib/lua/5.2/?/init.lua;./?.lua
PANIC: unprotected error in call to Lua API (...090-B99A-4B9B-ADAC-F0BEF46B6EA4/LuaThirdTry.app/test.lua:5: module 'mylib' not found:
no field package.preload['mylib']
no file '/usr/local/share/lua/5.2/mylib.lua'
no file '/usr/local/share/lua/5.2/mylib/init.lua'
no file '/usr/local/lib/lua/5.2/mylib.lua'
no file '/usr/local/lib/lua/5.2/mylib/init.lua'
no file './mylib.lua'
no file '/usr/local/lib/lua/5.2/mylib.so'
no file '/usr/local/lib/lua/5.2/loadall.so'
no file './mylib.so')
When I add a line modifying package.path, I got it running correctly:
--main.lua modified
print(package.path)
package.path = package.path .. ";/var/mobile/Applications/C6CEF090-B99A-4B9B-ADAC-F0BEF46B6EA4/LuaThirdTry.app/?.lua"
require("mylib")
But this is an absolute path, which should definitely be avoided.
One way to solve this problem is to provide lua a function from c, which returns the full path of lua file in ipa bundle at runtime to lua script, and concatenate the package.path with that path, but I think that shouldn't be the "official" way of doing this.
I noticed "./?.lua" inside package.path variable, I just wonder why mylib.lua can't be found, isn't it for files within the same directory?
Sorry for the blah, so the question is: how do I do the "require" decently in iOS environment?
Okay, I finally find a good answer and the job is done, thank to this answer.
So, the solution is to modify the path within c++ code, add this function
#include <string>
int setLuaPath(lua_State* L, const char* path) {
lua_getglobal(L, "package");
lua_getfield(L, -1, "path"); // get field "path" from table at top of stack (-1)
std::string cur_path = lua_tostring(L, -1); // grab path string from top of stack
cur_path.append(";"); // do your path magic here
cur_path.append(path);
lua_pop(L, 1); // get rid of the string on the stack we just pushed on line 5
lua_pushstring(L, cur_path.c_str()); // push the new one
lua_setfield(L, -2, "path"); // set the field "path" in table at -2 with value at top of stack
lua_pop(L, 1); // get rid of package table from top of stack
return 0; // all done!
}
and then, call this function when init lua_State:
// yourfile.cpp
void runLua() {
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
OCCaller oc_caller;
std::string bundlePath = oc_caller.get_ios_bundle_path();
bundlePath.append("/?.lua");
setLuaPath(L, bundlePath.c_str());
....
}
your oc_caller class might look like this:
// OCCaller.h
#ifndef __LuaThirdTry__OCCaller__
#define __LuaThirdTry__OCCaller__
#include <iostream>
class OCCaller {
public:
OCCaller();
~OCCaller();
std::string get_ios_bundle_path();
};
#endif
impl file:
// OCCaller.mm
#include "OCCaller.h"
#import <Foundation/Foundation.h>
OCCaller::OCCaller() { }
OCCaller::~OCCaller() { }
std::string OCCaller::get_ios_bundle_path() {
NSString *bundlePath = [[NSBundle mainBundle]resourcePath];
return std::string([bundlePath UTF8String]);
}
Most likely, "." is not the folder containing main.lua, but a working directory (such as where xcode runs from). The app that runs your script probably runs it via a path, like
lua /full/path/to/your/main.lua
So having ./?.lua in LUA_PATH does not help here. Instead, you should have the script run a command to determine where it is running from, and append that to package.path. This should be the path part of arg[0]. So you could try (not tested):
local scriptPath = arg[0]
local dir = string.match(scriptPath, '^.*/')
package.path = package.path .. ';' .. dir .. '?.lua'
The arg is automatically populated by the interpreter, see Section 6 of Lua ref man.
You definitely don't need C to do what you want.
This is a revision on Bryophyte's answer. To me, this was far too complex. I'm also not sure why he did all these extra classes and used C++ strings instead of NSStrings. Here is my revised and hopefully easier to understand iOS code based on this solution:
-(void)addBundlePathToLuaState:(lua_State*)L
{
lua_getglobal(L, "package");
lua_getfield(L, -1, "path"); // get field "path" from table at top of stack (-1)
const char* current_path_const = lua_tostring(L, -1); // grab path string from top of stack
NSString* current_path = [NSString stringWithFormat:#"%s;%#/?.lua", current_path_const, [[NSBundle mainBundle]resourcePath]];
lua_pop(L, 1); // get rid of the string on the stack we just pushed on line 5
lua_pushstring(L, [current_path UTF8String]); // push the new one
lua_setfield(L, -2, "path"); // set the field "path" in table at -2 with value at top of stack
lua_pop(L, 1); // get rid of package table from top of stack
}

Calling Library in Lua

I have created a Wireshark dissector in Lua for an application over TCP. I am attempting to use zlib compression and base64 decryption. How do I actually create or call an existing c library in Lua?
The documentation I have seen just says that you can get the libraries and use either the require() call or the luaopen_ call, but not how to actually make the program find and recognize the actual library. All of this is being done in Windows.
You can't load any existing C library, which was not created for Lua, with plain Lua. It's not trivial at least.
*.so/*.dll must follow some specific standard, which is bluntly mentioned in programming in Lua#26.2 and lua-users wiki, code sample. Also similar question answered here.
There are two ways You could solve Your problem:
Writing Your own Lua zlib library wrapper, following those standards.
Taking some already finished solution:
zlib#luapower
lua-zlib
ffi
Bigger list #lua-users wiki
The same applies to base64 encoding/decoding. Only difference, there are already plain-Lua libraries for that. Code samples and couple of links #lua-users wiki.
NOTE: Lua module package managers like LuaRocks or
LuaDist MIGHT save You plenty of time.
Also, simply loading a Lua module usually consists of one line:
local zlib = require("zlib")
The module would be searched in places defined in Your Lua interpreter's luaconf.h file.
For 5.1 it's:
#if defined(_WIN32)
/*
** In Windows, any exclamation mark ('!') in the path is replaced by the
** path of the directory of the executable file of the current process.
*/
#define LUA_LDIR "!\\lua\\"
#define LUA_CDIR "!\\"
#define LUA_PATH_DEFAULT \
".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \
LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua"
#define LUA_CPATH_DEFAULT \
".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll"
#else
How do I actually create or call an existing c library in Lua?
An arbitrary library, not written for use by Lua? You generally can't.
A Lua consumable "module" must be linked against the Lua API -- the same version as the host interpreter, such as Lua5.1.dll in the root of the Wireshark directory -- and expose a C-callable function matching the lua_CFunction signature. Lua can load the library and call that function, and it's up to that function to actually expose functionality to Lua using the Lua API.
Your zlib and/or base64 libraries know nothing about Lua. If you had a Lua interpreter with a built-in FFI, or you found a FFI Lua module you could load, you could probably get this to work, but it's really more trouble than it's worth. Writing a Lua module is actually super easy, and you can tailor the interface to be more idiomatic for Lua.
I don't have zlib or a base64 C library handy, so for example's sake lets say we wanted to let our Lua script use the MessageBox function from the user32.dll library in Windows.
#include <windows.h>
#include "lauxlib.h"
static int luaMessageBox (lua_State* L) {
const char* message = luaL_checkstring(L,1);
MessageBox(NULL, message, "", MB_OK);
return 0;
}
int __declspec(dllexport) __cdecl luaopen_messagebox (lua_State* L) {
lua_register(L, "msgbox", luaMessageBox);
return 0;
}
To build this, we need to link against user32.dll (contains MessageBox) and lua5.1.dll (contains the Lua API). You can get Lua5.1.lib from the Wireshark source. Here's using Microsoft's compiler to produce messagebox.dll:
cl /LD /Ilua-5.1.4/src messagebox.c user32.lib lua5.1.lib
Now your Lua scripts can write:
require "messagebox"
msgbox("Hello, World!")
Your only option is to use a library library like alien. See my answer Disabling Desktop Composition using Lua Scripting for other FFI libraries.

Using mingw with opencv -- init error

I use Eclipse CDT for developing C with mingw. I also add opencv libary. Everything compiled without problems. But if I start the compiled application (using a opencv-function) there is an init error. If I only include the .h-files without using a function it works.
The code:
#include <opencv2/opencv.hpp>
using namespace std;
int main() {
cout << "!!!Streaming!!!" << endl; // prints !!!Streaming!!!
// Nothing but create a window
cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);
cvMoveWindow("mainWin", 100, 100);
cvWaitKey(0);
return 0;
}
Error-Image: http://i.stack.imgur.com/zdmT7.png
If I do not use a cv.. - function there will be no init error. Even if I include opencv2/opencv.hpp
I do not have an idea how it works.
Hope you can help.
I found the solution. The opencv-dll-files for mingw are damaged. I rename the visualstudio dlls to the names of the mingw-dlls and put it directly to in the exe folder and it works.

Resources