Check JNI calls correctness in Compile time - java-native-interface

We use a banch of JNI calls (C++ -> Java) in our project. Sometimes me rename methods, do refactoring, etc. So it's will be nice to check every call in compile time. Calls looks like
m_getDeviceIdMid = getEnv()->GetMethodID(jAdapterClass, "getDeviceId", " ()Ljava/lang/String;");
getEnv()->CallObjectMethod(m_jAdapter, m_getDeviceIdMid)
Do you know a way to do it? (Maybe with annotations or something similar)

Related

Dynamically create DLL export functions without having the preprocessor involved in MSVC 2015?

Is it possible to dynamically create __declspec(dllexport)'ed functions without having the preprocessor involved in MSVC 2015?
I'm creating a DLL plugin-creation toolkit for some kind of measurement software and want to make the later client-programmer being able to add some kind of "extra-features" to the plugin in the DllMain, e.g.:
// Create a new instance of the custom driver
MyPluginDriver *myPluginDriver = new MyPluginDriver();
// Assign it to the core DLL
pluginCore.addDriver(myPluginDriver);
For each of this addDrivercalls, the DLL later has to provide a callback function, whose name can be freely chosen. The main app expects the names of those functions getting passed by request in another callback.
So, what would be the 'best practice' for generating those extern "C" functions dynamically whithout #define's and stuff?
Maybe some kind of Lambda way?
EDIT:
I think I've forgot to mention that it's a commercially available measurement software for which I'm writing that PDK. It's a fixed interface (and a fairly complex one, too) of hard-coded and expected function names by the app for the general callbacks. There's only that particular callback expecting some function names to call for measurement cycles which is relevant here.

Call a cocoa/obj-c method from a C++ dylib in MAC OS X

Since I am fairly new to Objective-C programming language, I'm facing a huge problem: how can I call a method of my application (made in Objective-C) from my dynamically loaded library (made in C++), by passing it some parameters?
I've been digging the web for a couple of days with no luck. The only thing I found is about IMP, but I'm not sure if that's what I need.
You actually have a plethora of options here.
If the dylib is one of your own, you can compile it as Objective-C++ for Mac OS X and #ifdef the objective-C calls (or not if you are only targeting Mac OS)
Both Obj-C and C++ can make use of C interfaces, so you could write an adapter layer in C (remember Obj-c is a strict superset of C) and expose it for the dylib to call the C functions which then call the Obj-C code.
You can use Blocks, which work in C, C++, and of course Obj-C
you can include the objective-c runtime (see documentation) and muck with that (This is where you would use the *IMP thing you mentioned).
Yet another option might be to use Objective C++ from the Cocoa side to setup C++ objects and expose those to the dylib. How you would go about this really depends on what the library is and how it is used etc; we need to know more about the dylib and how it is being used to elaborate on this.
Since you specifically mention using an IMP lets talk a bit more in depth about that. The declaration is typedef void (*IMP)(id self, SEL _cmd, ...); which you can see takes a pointer to an Obj-C objects, and a SEL (selector), which is just a special C-String representation of the method. You can read more about both SEL and IMP in the documentation.
You can also make use of the runtime's C functions such as objc_msgSend to call a method by passing a pointer to the object and a SEL just like with IMP.
This should be enough information to get you started. Thanks for this question BTW, I never really sat down and thought about all the possible ways to combine C++ with Objective-C before. Odds are I even missed something ;)
You can use objective c runtime
include <objc/runtime.h>
objc_msgSend(id, SEL, arg0, ...)
where
id - is the object where you want to send message
SEL - is struct pointer, describing message you send.
arg0,... are the arguments that you pass to selector.
For more understanding of runtime, see the source code http://www.opensource.apple.com/source/objc4/
Also you can cast IMP address, and call the function.
int(* foo)(id, SEL, arg) = IMP;
foo(someObject, #selector(someMessage), arg);

How to catch up specific method calls in a kind of logging mechanism

I'm implementing a logger for an OpenGL application ( the only reason I'm mentioning it is that it runs in a loop ). I'd like to somehow log every method call or some group of method calls of some classes, every time they are called.
My initial approach was to place the required logger function call in all the methods ( which actually kind of works like comments :) ) but I got really tired of it really fast, so I started looking for a more effective way. I searched google for some time, but since I don't really know what I'm looking for, I ran out of ideas.
The best thing for my case would be some kind of magical method, that would be called every time I invoked any other class method, idealy with name and params string as a parameter for this method. ( kind of PHP - like magic method __call() - but that one works only if method is not defined ). I don't know what I am looking for, if something like that even exists, and if it does, what do we call it?
P.S.:
my logging works on macros, so no worries for performance there :)
#if DEV_LOG
#define log_init() logInit()
#define log_write(a,b) writeToLog(to_str(a), to_str(b))
#else
#define log_init()
#define log_write(a,b)
#endif
( And if there's a nicer way to do this, let me know, please :) )
Thank you!
1st I have to re-cite my co-answerer Filip here
C++ doesn't have this kind of "magical method", so you are stuck with explicitly stating a function call inside every member-function, if you'd like one to be made.
Such stuff is implemented as compiler specific features like the GCC profiling. There will be code generated to track for function calls, their parameters, and where these actually were called from and how often.
The general usage is to compile and link your code with special compiler flags that will generate this code. When your code is run, this information will be stored along specific kind of databases, that can be analyzed with a separate tool after running (as e.g. gprof for the GCC toolchain).
A similar tooling suite is used for retrieving code coverage of certain program runs (e.g. testsuites for your code): gcov A Test Coverage Program
C++ doesn't have this kind of "magical method", so you are stuck with explicitly stating a function call inside every member-function, if you'd like one to be made.
You could instead use a debugger to track the calls made, the program you've written shouldn't have to be responsible for questions such as "what code is called, when and with what?"; that's the exact question a profiler, or a debugger, was made to answer.

Google test: how to check a global C (C++) function was called

I am writing test cases for a scripting language which is embedded in a C (or C++) application and one of the features is that the scripting language calls a method from the "host" program. The entire project is using the google test framework, and down here is one of the tests:
TEST(Functions, ExternalCalling)
{
SCRIPT_START
" \
extern void external_callee(int, int); \
external_callee(1,2); \
"
SCRIPT_END
}
NAP_EXPORTS
void external_callee(nap_int_t a, nap_int_t b)
{
fprintf(stderr, "\na=%"PRINT_d", b=%"PRINT_d"\n", a, b);
if(a != 1 || b != 2) FAIL();
}
Do not mind the SCRIPT_START and SCRIPT_END macros, they just create/destroy scripting language objects (NAP_EXPORTS is defined as extern "C" so that the dynamic library loader can resolve the name).
As you can see the script defines an external method (from the host application) and then calls it. Right now I am sure that the method is called since I can see on the stderr/output the values of a and b but yeah... this has the feeling of manual testing :) How can I use the google test framework to make sure that the method actually was called without having to look on the screen? (I'd like to avoid hackish solutions, like use a global flag...)
What you actually want to do is mock the function.
Look at mocking frameworks like google-mock.
The EXPECT_CALL macro lets you specify call occurences (with argument filtering).
See also This SO Question how to create C trampolins to hide C++ interfaces behind C code.
if you also want to have a real result you also might be interested in the invoke function that allows you to forward arguments to a real implementation.
the google mock cookbook has recipes for all use patterns above.
Here are a few ideas, in order from least to most insidious:
Make your function return a string instead of printing it internally. Or return something, at least.
Add an (optional) FILE* parameter to external_callee() and write there instead of hard-coding stderr. Then your test harness can hook it up to a temporary file or something fancier.
Make a global variable which is the FILE* to write to. Default it to stderr but let the test harness change it. Basically like the previous idea but without modifying the signature.
Have your test harness reopen the stderr file descriptor as a pipe. Call the function and then try to read from that pipe.
Override printf() in your test program. Yes, you can probably do this--try it! Just define printf() yourself with the same signature and that one should get called. Then you can do anything you want.

How to implement Python function exec() in C++?

The Python function exec() is a very good tool for programming.
For example:
/******************************************************
* we have array names={"ali","hamed"}
* goal is declare string ali="ali" and hamed="hamed"
******************************************************/
Python code:
# used for command
# below line is a syntax python
# in python we dont declare variable
list=["ali","hamed"] #python syntax
#in python we dont wite {
#python work with tab insteed of {}
for i in list:
temp = i + ' = "' + i + '"' #temp is a string
exec(temp)
My question: Is there a similar function exists in C++? If not, how to implement it in C++?
Python's exec, and similar features in other languages (i.e. eval in JavaScript) only work because those are interpreted languages where variables are defined at run time.
You can't do what you're asking in directly C++ because it's a compiled language that requires that all variables and their names are known at compile time.
You can do it, but it's not trivial, and it will only work on
systems where a C++ compiler is installed. Basically, C++ is
compiled, so if you want to execute some string which is C++,
you'll have to compile it: write it to a file (probably with
additional boilerplate like some includes), invoke the compiler
(with system) to build a DLL, and then load the DLL.
In practice, even if you went to all that effort, you'd probably
find it less useful than you think. Because C++ requires static
declarations for just about everything, it's much harder to
write small snippets like that and have them usable. (You
would, for example, have to wrap it in a function, and generate
extern for all of the variables it uses.) C++ doesn't support
this sort of thing for software engineering reasons; the very
features which make languages like Python so flexible for small,
quickly written programs, cause severe maintenance problems when
used in large scale robust software. Different languages are
designed for different purposes. It's very easy to create
a mixed language system using Python for the top level glue
(where you would want a facility such as you describe), and
calling into C++ for the heavy work (where such a facility would
allow the user to trigger core dumps at will).
Alternatively, you can implement a small language in C++. For
keeping user defined variables, for example, use std::map,
rather than declaring the variables. (That is, after all, what
Python does under the hood.)
If you are planning to use strings as parameters,it is NOT a good idea!
you can simply use an id generator function and give an id to every string that you are gonna use ,or if you are using a class you can put that function in the constructor.
no need to that exec() at all!!