I have a working python wrapper for C++ code (as suggested here Calling C/C++ from python?
) using ctypes. But the problem is with main function of the code. When I do something like
extern "C" {
void call_main(){ main();}
}
in my c++ code and then call this function via python wrapper
...
lib = cdll.lib('./mylib.so')
def run():
lib.call_main()
-> I get "segmentation fault".
The funny part is that when i copy paste my main method code into function called e.g. test (so it is int test() {....#pasted code...} in c++ code), extern it and then call lib.test()
=> And eveything works fine... So it must be a problem with the main function being called main or something
In C++ calling main() recursively is not allowed ( see 3.6.1, basic.start.main, paragraph 3). Also, you need a C++ aware entry point when you want to call C++ functionality. You can sometimes get away with calling C++ functionality without this but what is going to work and what is not isn't entirely straight forward. The obvious problem is with global objects needing initialization.
Just put the code you want to call into a different function and call this.
Related
I want to instrument some code that gets executed before any other code in my module.
I thought about calling the code in the start of the main function. But there is not always a main function or it is not always named "main". Or it is a library and it doesn't even have a main function.
Are there some other, smarter ways?
You can put the code you want to run early into a function and add that function to llvm.global_ctors. This is the equivalent of using __attribute__((constructor)) in C or C++.
To do this from a pass, you can use the llvm::appendToGlobalCtors function, which is declared in llvm/Transforms/Utils/ModuleUtils.h.
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.
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
I am busy with a C++ project on IBM i and is trying to call an RPG procedure that is in a service program, but I am not sure how to do that.
I only find examples on the internet and the documentation that shows how to call an RPG program (*PGM) object by defining it as follows:
extern "OS"
{
void RPGPROGRAM(void);
}
int main()
{
RPGPROGRAM();
return 0;
}
The documentation says they are calling an RPG "procedure" but if you look at the actual source it is just a RPG program (*PGM) object that they call from within C++ using #pragma map.
Lets say I have the following RPG service program (lets name it RPGSP) with a procedure named rpg_doSomething defined in it:
ctl-opt nomain;
dcl-proc rpg_doSomething export;
dcl-pi *n int(10);
dcl-parm p_test char(20);
end-pi;
p_test = "It Works!!";
return 1;
end-proc;
How should I declare and call the above procedure in my C++ program?
I have tried declaring it within the extern block but it ends up looking for the rpg_doSomething object at runtime and cannot find it. I have also tried binding the service program to the C++ program when compiling but that does not work either.
Any help on this would be appreciated.
First off which C++ compiler are you using?
The native ILE one? Then it should be pretty easy. Pretty sure you just need:
extern "RPG" on the function declaration.
Or the AIX on in PASE? Then take a look at Calling ILE procedures
One thing to note, RPGLE is case insensitive and by default, uppercases names. While C/C++ is case sensitive. Your C++ program needs to be calling RPG_DOSOMETHING or you need to apply a case sensitive name to the RPG procedure using EXTPROC('rpg_DoSomething')
I have a C++ program:
class X
{
private:
int a;
public:
int func(char *str);
};
Now I want to call the function func in my Python program. How can I do it?
I have successfully called C functions from my Python program using ctypes.
However I can't seem to figure out how to call functions defined inside C++ objects.
I have already worked with ctypes, so I would like to figure out how to accomplishing it that way. However I'm open to other techniques. Also my project puts a constarint that I am not supposed to use wrapper function in my C++ program.
Check out Boost::Python.
You tagged the question ctypes, but you cannot instantiate a C++ object directly from ctypes. You can wrap the C++ object in a C interface and then use ctypes. Or you could write a Python extension module which could include C++ code.
An alternative to Boost.Python is SWIG.
try http://swig.org/
years ago i wrapped some c/c++ code to use them in wxPython with swig.
i cannot remember too much details but i think swig is easy to use.
Hope that helps.