How to wrap an init/cleanup function in Boost python - c++

I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library.
While wrapping the basic library API calls is quite simple (nothing special, just regular function calls and very common parameters), I don't know how to properly wrap the initialization/cleanup functions:
As it stands, my C++ library requires the caller to first call mylib::initialize() when the program starts, and to call mylib::cleanup() before it ends (actually there is also an initializer object that takes care of that, but it is probably irrelevant).
How should I wrap this using boost python ?
Forcing a Python user to call mymodule.initialize() and mymodule.cleanup() seems not very pythonic. Is there any way to that in an automatic fashion ? Ideally, the call to initialize() would be done transparently when the module is imported and the call to cleanup() also done when the python script ends.
Is there any way to do that ? If not, what is the most elegant solution ?
Thank you.

You could try to do a guard object and assign it to a hidden attribute of your module.
struct MyLibGuard
{
MyLibGuard() { myLib::initialize();}
~MyLibGuard() { myLib::cleanup();}
};
using namespace boost::python;
BOOST_PYTHON_MODULE(arch_lib)
{
boost::shared_ptr<MyLibGuard> libGuard = new MyLibGuard();
class_<MyLibGuard, boost::shared_ptr<MyLibGuard>, boost::noncopyable>("MyLibGuard", no_init);
scope().attr("__libguard") = libGuard;
}

Related

How does it work and compile a C++ extension of TCL with a Macro and no main function

I have a working set of TCL script plus C++ extension but I dont know exactly how it works and how was it compiled. I am using gcc and linux Arch.
It works as follows: when we execute the test.tcl script it will pass some values to an object of a class defined into the C++ extension. Using these values the extension using a macro give some result and print some graphics.
In the test.tcl scrip I have:
#!object
use_namespace myClass
proc simulate {} {
uplevel #0 {
set running 1
for {} {$running} { } {
moveBugs
draw .world.canvas
.statusbar configure -text "t:[tstep]"
}
}
}
set toroidal 1
set nx 100
set ny 100
set mv_dist 4
setup $nx $ny $mv_dist $toroidal
addBugs 100
# size of a grid cell in pixels
set scale 5
myClass.scale 5
The object.cc looks like:
#include //some includes here
MyClass myClass;
make_model(myClass); // --> this is a macro!
The Macro "make_model(myClass)" expands as follows:
namespace myClass_ns { DEFINE_MYLIB_LIBRARY; int TCL_obj_myClass
(mylib::TCL_obj_init(myClass),TCL_obj(mylib::null_TCL_obj,
(std::string)"myClass",myClass),1); };
The Class definition is:
class MyClass:
{
public:
int tstep; //timestep - updated each time moveBugs is called
int scale; //no. pixels used to represent bugs
void setup(TCL_args args) {
int nx=args, ny=args, moveDistance=args;
bool toroidal=args;
Space::setup(nx,ny,moveDistance,toroidal);
}
The whole thing creates a cell-grid with some dots (bugs) moving from one cell to another.
My questions are:
How do the class methods and variables get the script values?
How is possible to have c++ code and compile it without a main function?
What is that macro doing there in the extension and how it works??
Thanks
Whenever a command in Tcl is run, it calls a function that implements that command. That function is written in a language like C or C++, and it is passed in the arguments (either as strings or Tcl_Obj* values). A full extension will also include a function to do the library initialisation; the function (which is external, has C linkage, and which has a name like Foo_Init if your library is foo.dll) does basic setting up tasks like registering the implementation functions as commands, and it's explicit because it takes a reference to the interpreter context that is being initialised.
The implementation functions can do pretty much anything they want, but to return a result they use one of the functions Tcl_SetResult, Tcl_SetObjResult, etc. and they have to return an int containing the relevant exception code. The usual useful ones are TCL_OK (for no exception) and TCL_ERROR (for stuff's gone wrong). This is a C API, so C++ exceptions aren't allowed.
It's possible to use C++ instance methods as command implementations, provided there's a binding function in between. In particular, the function has to get the instance pointer by casting a ClientData value (an alias for void* in reality, remember this is mostly a C API) and then invoking the method on that. It's a small amount of code.
Compiling things is just building a DLL that links against the right library (or libraries, as required). While extensions are usually recommended to link against the stub library, it's not necessary when you're just developing and testing on one machine. But if you're linking against the Tcl DLL, you'd better make sure that the code gets loaded into a tclsh that uses that DLL. Stub libraries get rid of that tight binding, providing pretty strong ABI stability, but are little more work to set up; you need to define the right C macro to turn them on and you need to do an extra API call in your initialisation function.
I assume you already know how to compile and link C++ code. I won't tell you how to do it, but there's bound to be other questions here on Stack Overflow if you need assistance.
Using the code? For an extension, it's basically just:
# Dynamically load the DLL and call the init function
load /path/to/your.dll
# Commands are all present, so use them
NewCommand 3
There are some extra steps later on to turn a DLL into a proper Tcl package, abstracting code that uses the DLL away from the fact that it is exactly that DLL and so on, but they're not something to worry about until you've got things working a lot more.

Using cjson in embedded Lua in C++

I have a C++ program that creates a lua_State and run custom Lua script. If I would like to have the lua_State pre-load cjson instead of requiring calling "require" in the Lua code, can I know whether it is possible and how can I do that?
Yes, it's possible. Use luaL_requiref for that. Use this or this function as argument. You'll need to link the cjson code to your executable, and the compiler would probably appreciate a function declaration for the luaopen_* functions. If you use Lua 5.1 (which doesn't have luaL_requiref yet) you can use or steal from Compat-5.3.
You could call require once through C++ and make a global variable out of the return value if you don't want to call require in scripts.
For example in C++ do:
if (luaL_dostring(L, "cjson = require(\"cjson\")")) // run code
std::cout << luaL_checkstring (L, -1) << std::endl; // print error
and after that you can use cjson in your scripts like cjson.new() without any require or such calls as it exists as a global variable.
Since require was used by C++ then calling require in lua later on will not run the cjson file again unlike using dofile or similar

directly calling from what user inputs and Is there a concept of generating a function at run time?

Is there a way out to call a function directly from the what the user inputs ?
For example : If the user inputs greet the function named greet is called.
I don't want any cases or comparison for the call to generate.
#include <iostream>
#include<string>
using namespace std;
void nameOfTheFunction(); // prototype
int main() {
string nameOfTheFunction;
getline(cin,nameOfTheFunction); // enter the name of Function
string newString = nameOfTheFunction + "()"; // !!!
cout << newString;
// now call the function nameOfTheFunction
}
void nameOfTheFunction() {
cout << "hello";
}
And is there a concept of generating the function at run time ?
You mean run time function generation ??
NO.
But you can use a map if you already know which all strings a user might give as input (i.e you are limiting the inputs).
For the above you can probably use std::map &lt std::string, boost::function &lt... &gt &gt
Check boost::function HERE
In short, no this isn't possible. Names in C++ get turned into memory offsets (addresses), and then the names are discarded**. At runtime C++ has no knowledge of the function or method names it's actually running.
** If debug symbols are compiled in, then the symbols are there, but impractical to get access to.
Generating a function at runtime has a lot of drawbacks (if it is possible at all) and there is generally no good reason to do it in a language like C++. You should leave that to scripting languages (like Perl or Python), many offer a eval() function that can interpret a string like script code and execute it.
If you really, really need to do have something like eval() in a compiled language such as C++, you have a few options:
Define your own scripting language and write a parser/interpreter for it (lots of work)
Define a very simple imperative or math language that can be easily parsed and evaluated using well-known design patterns (like Interpreter)
Use an existing scripting language that can be easily integrated into your code through a library (example: Lua)
Stuff the strings of code you want to execute at runtime through an external interpreter or compiler and execute them through the operating system or load them into your program using dlopen/LoadLibrary/etc.
(3.) is probably the easiest and best approach. If you want to keep external dependencies to a minimum or if you need direct access to functionality and state inside your main program, I suggest you should go for (2.) Note that you can have callbacks into your own code in that case, so calling native functions from the script is not a problem. See here for a tutorial
If you can opt for a language like Java or C#, there's also the option to use the compiler built into the runtime itself. Have a look here for how to do this in Java

Convert C++ Syntax to Objective C

My background experience is C/C++/C#.
I am using a C++ library in an xcode project (to be specific the library is PJSIP). To use the library i have to wire couple of callbacks to my code like this:
SipTest.m
#include < pjsua-lib/pjsua.h >
static void on_reg_state(pjsua_acc_id acc_id)
{
// Do work
}
static void Init()
{
// pjsua_config and psjua_config_default are defined in the header file from pjsip
pjsua_config cfg;
psjua_config_default(&cfg);
cfg.cb.on_regstate = &on_reg_state;
}
I want to switch this C++ sytnax to Objective C
so I did:
+(void) on_reg_state:(pjsua_acc_id) acc_id
{
// Do work
}
+(void) Init
{
pjsua_config cfg;
psjua_config_default(&cfg);
cfg.cb.on_regstate = &on_reg_state; // ***** this is causing compile error
// I tried [CLASS NAME on_reg_state] and i get runtime error
}
I tried to search for delegate in Objective C but i could not find an a similar case where the callback is already implemented in C++ and you want to use it with Objective-C syntax.
Thanks
First of all, there's absolutely no need to convert anything at all. It is perfectly fine to call C++ libraries from Objective-C.
Secondly, whats causing the compiler error is that you're trying to stick a method in a place where there should be a function pointer. You can't make a function pointer out of an Objective-C method using the & Operator. Simply keep your on_reg_state() function and use it as you did before, that's how you do callbacks in Apple's C-based frameworks, too (which you'll need as soon as you move beyond what the high-level Objective-C APIs provide).
And thirdly, your + (void)Init method seems a bit strange. I would strongly discourage you to write a method called Init (capitalized). If you intend to write an initializer, it should be - (id)init, i.e. lowercase and returning id. And don't forget to call the designated initializer of its superclass, check its return value, assign it to self, and return it at the end of the init method (see Implementing an Initializer in Apple's documentation if you're not familiar with that). And if your method is not an initializer, use a different name, e.g. - (void)createConfig.
in this case you'd want to use selectors.
+(void) on_reg_state:(pjsua_acc_id) acc_id
{
// Do work
}
+(void) Init
{
pjsua_config cfg;
psjua_config_default(&cfg);
cfg.cb.on_regstate_selector = #selector(on_reg_state:);
cfg.cb.target = self; //Self here is the class object in your 'Init' method, which is poorly named.
//Use this like [cfg.cb.target performSelector:cfg.cb.on_regstate_selector withObject:...etc]
}

Releasing Python GIL while in C++ code

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.