Convert C Code to Delphi - c

I need to convert this Line from C to Delphi.
Int CALLBACK EXPORT EXAMPLEFUNCTION(VOID){
SETEVENT(hasync);
Return Success;
}
Please i need some help.
thanks ;)

Kind of guessing here, because the style's really messy, but I think that would translate something like this:
const Success = 1; //or whatever; might not be 1.
//assume a const definition for a value
//called Success exists somewhere in scope
function EXAMPLEFUNCTION(): integer; stdcall; //CALLBACK = stdcall calling convention
begin
SETEVENT(hasync); //hopefully this makes sense in context
result := Success;
end;
That's the best I can do without further context. The EXPORT declaration is a preprocessor macro, and it (probably) means that this is part of a DLL and that this is a function that's supposed to be callable by programs that load the DLL. In Delphi, that's not part of the function definition; instead, you put it in an exports clause.

Related

Z3_mk_config and Z3_mk_context deprecated (Z3 C API). Which functions should we use now?

I'm using the C API of Z3. I've checked the examples, and Z3_mk_config() and Z3_mk_context (Z3_config c) are used to create contexts, e.g.,
Z3_config cfg;
Z3_context ctx;
cfg = Z3_mk_config();
Z3_set_param_value(cfg, "model", "true");
//...
ctx = Z3_mk_context(cfg);
However, the documentation says that all these functions are deprecated, but don't mention which functions should be used now instead.
Does anyone know which functions should be used now to create configurations and contexts?
Any help would be greatly appreciated. Thank you!
TLDR:
Use Z3_mk_config to create a Z3_config.
Use Z3_global_param_set to set configs globally.
Use Z3_set_param_value to set context-specific configs.
If you don't have any config to set, simply
make a Z3_config with Z3_mk_config,
create your context with it,
and then delete it with Z3_del_config.
The comment by SergeyLebedev is probably referencing to this remark in the doc
In previous versions of Z3, the Z3_config was used to store global and
module configurations. Now, we should use Z3_global_param_set.
I was going through the source repo the past few days. In the example file test_capi.c, they use this mk_context function a lot, which is defined in the same file with
Z3_context mk_context()
{
Z3_config cfg;
Z3_context ctx;
cfg = Z3_mk_config();
ctx = mk_context_custom(cfg, error_handler);
Z3_del_config(cfg);
return ctx;
}
where mk_context_custom is defined in the same file with
Z3_context mk_context_custom(Z3_config cfg, Z3_error_handler err)
{
Z3_context ctx;
Z3_set_param_value(cfg, "model", "true");
ctx = Z3_mk_context(cfg);
Z3_set_error_handler(ctx, err);
return ctx;
}
So it looks like Z3_mk_config and Z3_set_param_value are still used.
The doc says that stuff like Z3_config and Z3_context are supposed to be "opaque pointers". However, chasing it to the source, it looks like Z3_config is declared as a struct without the specific content but seems like wherever it's used it's cast to context_params which is defined clearly as a class.
The type Z3_config is declared in z3_api_h with
DEFINE_TYPE(Z3_config);
where DEFINE_TYPE(T) is a macro defined in z3_macros.h and expands to typedef struct _ ## T *T. So really Z3_config is only prototypically declared as a struct.
The function Z3_mk_config, the constructor for a Z3_config, declared in z3_api.h with
Z3_config Z3_API Z3_mk_config(void);
, is defined in api_config_params.cpp as
Z3_config Z3_API Z3_mk_config(void) {
try {
memory::initialize(UINT_MAX);
LOG_Z3_mk_config();
Z3_config r = reinterpret_cast<Z3_config>(alloc(context_params));
RETURN_Z3(r);
} catch (z3_exception & ex) {
// The error handler is only available for contexts
// Just throw a warning.
warning_msg("%s", ex.msg());
return nullptr;
}
}
within an extern "C" block. Note that Z3_API is a macro also defined in z3_macros.h to set __attribute__ ((visibility ("default"))) and alloc is a macro defined in memory_manager.h with #define alloc(T,...) new (memory::allocate(sizeof(T))) T(__VA_ARGS__) and RETURN_Z3 is a macro defined in some file generated by the file update_api.py with #define RETURN_Z3(Z3RES) if (_LOG_CTX.enabled()) { SetR(Z3RES); } return Z3RES.
It appears that, when a Z3_config is created, a memory block of the size of a context_params is allocated and cast as Z3_config, and context_params is in fact a class defined clearly in context_params.h. I omit the content because it's not relevant right now.
class context_params {
....
};
Next, Z3_set_param_value is defined in api_config_params.cpp with
void Z3_API Z3_set_param_value(Z3_config c, char const * param_id, char const * param_value) {
LOG_Z3_set_param_value(c, param_id, param_value);
try {
context_params * p = reinterpret_cast<context_params*>(c);
p->set(param_id, param_value);
}
catch (z3_exception & ex) {
// The error handler is only available for contexts
// Just throw a warning.
warning_msg("%s", ex.msg());
}
}
So it appears that the function first cast Z3_config back to context_params before using it like a normal object. I'm not an expert but this probably works because struct and class are almost the same underneath the hood.
On the other hand, in that exmaple file test_capi.c, they used Z3_global_param_set like so
....
cfg = Z3_mk_config();
....
/*
The current model finder for quantified formulas cannot handle injectivity.
So, we are limiting the number of iterations to avoid a long "wait".
*/
Z3_global_param_set("smt.mbqi.max_iterations", "10");
ctx = mk_context_custom(cfg, error_handler);
Z3_del_config(cfg);
s = mk_solver(ctx);
They did still use Z3_mk_config before making a context while using Z3_global_param_set to set configs. So I'd say there's nothing wrong with using Z3_mk_config to construct a Z3_config, and what the doc is saying is when you want to set something globally, don't access the Z3_config struct itself since you can't before casting it to a context_params anyway; use Z3_global_param_set instead. And when you want to set something specific to some specific context, use Z3_set_param_value.
The question remains that why would we want to switch between structs and classes? I don't know. I'm not at all familiar with C++, but I'm guessing, if not for the C API itself, it's for making the extern "C" part works for the Python API bindings.

duktape use common c function for multiple bound js functions

I'm trying to bind a common c function to multiple javascript functions using the duktape engine.
My problem is that i need to find out the name of the calling function inside the common c function. I feel like it's possible to implement this using the often referred javascript stack.
However i have no concrete idea on how to implement it. Does anybody have an idea on how to do this?
Below You can find my mwe. The function duk_get_invoking_function is meant to be pseudo code that emphasizes my intent.
#include "duktape.h"
duk_ret_t common_function(duk_context * ctx) {
const char * function_name;
//
// function_name = duk_get_invoking_function(ctx);
// e.g. function_name is "func_01"
//
return 0;
}
int main() {
duk_context * ctx;
ctx = duk_create_heap_default();
if (!ctx) {
return 1;
}
duk_push_c_function(ctx, common_function, DUK_VARARGS);
duk_put_global_string(ctx, "func_01");
duk_push_c_function(ctx, common_function, DUK_VARARGS);
duk_put_global_string(ctx, "func_02");
duk_push_c_function(ctx, common_function, DUK_VARARGS);
duk_put_global_string(ctx, "func_03");
duk_eval_string(ctx, "func_01('abc'); func_02(123); func_03();");
duk_destroy_heap(ctx);
return 0;
}
If I understood correctly you want multiple Ecmascript function objects to bind to the same native function -- and when that native function is called, figure out which Ecmascript function object was used in the call.
If so, you don't need to look at the call stack to do this: each duk_push_c_function() creates a new Ecmascript function object that points to the same native function. When the native function is called, you can use duk_push_current_function() to get access to the Ecmascript function used in the call. You can then distinguish between the Ecmascript function objects based on e.g. their properties which you set when you create them.

How can I use global variables used between two C function which are called in Modelica?

I have two function definitions in C which share some global variables. I want to call these functions in Modelica but I do not know how can I correctly keep the value of the global variable between two function calls.
file.c
/*Global variable definition*/
int* global_test1;
void FirstFunc (const int* init_value){
memcpy(global_test1, init_value, 2*sizeof(int));
}
void SecondFunc(int* some_output_variable){
memcpy(some_output_variable, global_test1, 2*sizeof(int));
}
calling_FirstFunc.mo
function calling_FirstFunc
input Integer[2,1] init_value = [3;3];
external "C" FirstFunc(init_value);
end;
calling_SecondFunc.mo
function calling_SecondFunc
output Integer[2,1] output_var;
external "C" SecondFunc(output_var);
end;
model.mo
model Calling_TwoFuncs
Integer[2,1] input_var = [3;5];
Integer[2,1] output_var;
equation
calling_FirstFunc(input_var);
when time>5.0 then
output_var = calling_SecondFunc();
end when;
end Calling_TwoFuncs;
Your sample code should almost work correctly. The C-functions will keep their state and work fine if (and only if) they are called in the order First, Second. You also need to allocate memory for global_test1... But this order is not guaranteed in the code. I suggest using external objects instead; then you can create multiple instances of the same model and not have a global state in the C-code (because you can malloc memory and return this for the constructor call; the First call). Note that you should probably pass the size of the vector to the constructor in order to be more general.

using a delphi callback function in a C dll

I'm using a C dll in a Delphi XE2 program without problem. One of the DLL function takes a function as argument.
Here is the prototype of the function:
var
LMX_MySetOption: function(LmxHandle: LMX_HANDLE;
eOption: _LMX_SETTINGS;
callback: TCallBackProcedure): LMX_STATUS cdecl
{$IFDEF WIN32} stdcall {$ENDIF};
The original prototype in C of the function was:
LMX_STATUS LMX_SetOption(LMX_HANDLE LmxHandle, LMX_SETTINGS eOption,
const void *pSetting);
TCallBackProcedure is defined as follow:
type
TCallBackProcedure = procedure(bla : Pointer) stdcall;
I'm calling the function this way:
LMX_MySetOption(LmxHandle, LMX_OPT_HEARTBEAT_EXIT_FUNCTION, UserExitRoutine);
The UserExitRoutine is definede as follow:
procedure UserExitRoutine(bla : Pointer) stdcall;
begin
...
end;
It's not working (access violation)
I can't modify the C dll.
Many thanks for any idea!
If is a C procedure don't use stdcall use cdecl .
And you can simply declare this
function LMX_MySetOption(LmxHandle: LMX_HANDLE;
eOption: _LMX_SETTINGS;
callback: Pointer): LMX_STATUS;cdecl;external 'yourmodule.dll';
procedure callback(bla:Pointer);cdecl;
begin
//Some code
end;
LMX_MySetOption(LmxHandle, LMX_OPT_HEARTBEAT_EXIT_FUNCTION, #callback);
It should work...if it doesn't maybe you don't know the exact nr of parameters that the function has...

How can I check that all my init functions have been called?

I am writing a large C program for embedded use. Every module in this program has an init() function (like a constructor) to set up its static variables.
The problem is that I have to remember to call all of these init functions from main(). I also have to remember to put them back if I have commented them out for some reason.
Is there anything clever I do to make sure that all of these functions are getting called? Something along the lines of putting a macro in each init function that, when you call a check_inited() function later, sends a warning to STDOUT if not all the functions are called.
I could increment a counter, but I'd have to maintain the correct number of init functions somewhere and that is also prone to error.
Thoughts?
The following is the solution I decided on, with input from several people in this thread
My goal is to make sure that all my init functions are actually being called. I want to do
this without maintaining lists or counts of modules across several files. I can't call
them automatically as Nick D suggested because they need to be called in a certain order.
To accomplish this, a macro included in every module uses the gcc constructor attribute to
add the init function name to a global list.
Another macro included in the body of the init function updates the global list to make a
note that the function was actually called.
Finally, a check function is called in main() after all of the inits are done.
Notes:
I chose to copy the strings into an array. This not strictly necessary because the
function names passed will always be static strings in normal usage. If memory was short
you could just store a pointer to the string that was passed in.
My reusable library of utility functions is called "nx_lib". Thus all the 'nxl' designations.
This isn't the most efficient code in the world but it's only called a boot time so that
doesn't matter for me.
There are two lines of code that need to be added to each module. If either is omitted,
the check function will let you know.
you might be able to make the constructor function static, which would avoid the need to give it a name that is unique across the project.
this code is only lightly tested and it's really late so please check carefully before trusting it.
Thank you to:
pierr who introduced me to the constructor attribute.
Nick D for demonstrating the ## preprocessor trick and giving me the framework.
tod frye for a clever linker-based approach that will work with many compilers.
Everyone else for helping out and sharing useful tidbits.
nx_lib_public.h
This is the relevant fragment of my library header file
#define NX_FUNC_RUN_CHECK_NAME_SIZE 20
typedef struct _nxl_function_element{
char func[NX_FUNC_RUN_CHECK_NAME_SIZE];
BOOL called;
} nxl_function_element;
void nxl_func_run_check_add(char *func_name);
BOOL nxl_func_run_check(void);
void nxl_func_run_check_hit(char *func_name);
#define NXL_FUNC_RUN_CHECK_ADD(function_name) \
void cons_ ## function_name() __attribute__((constructor)); \
void cons_ ## function_name() { nxl_func_run_check_add(#function_name); }
nxl_func_run_check.c
This is the libary code that is called to add function names and check them later.
#define MAX_CHECKED_FUNCTIONS 100
static nxl_function_element m_functions[MAX_CHECKED_FUNCTIONS];
static int m_func_cnt = 0;
// call automatically before main runs to register a function name.
void nxl_func_run_check_add(char *func_name)
{
// fail and complain if no more room.
if (m_func_cnt >= MAX_CHECKED_FUNCTIONS) {
print ("nxl_func_run_check_add failed, out of space\r\n");
return;
}
strncpy (m_functions[m_func_cnt].func, func_name,
NX_FUNC_RUN_CHECK_NAME_SIZE);
m_functions[m_func_cnt].func[NX_FUNC_RUN_CHECK_NAME_SIZE-1] = 0;
m_functions[m_func_cnt++].called = FALSE;
}
// call from inside the init function
void nxl_func_run_check_hit(char *func_name)
{
int i;
for (i=0; i< m_func_cnt; i++) {
if (! strncmp(m_functions[i].func, func_name,
NX_FUNC_RUN_CHECK_NAME_SIZE)) {
m_functions[i].called = TRUE;
return;
}
}
print("nxl_func_run_check_hit(): error, unregistered function was hit\r\n");
}
// checks that all registered functions were called
BOOL nxl_func_run_check(void) {
int i;
BOOL success=TRUE;
for (i=0; i< m_func_cnt; i++) {
if (m_functions[i].called == FALSE) {
success = FALSE;
xil_printf("nxl_func_run_check error: %s() not called\r\n",
m_functions[i].func);
}
}
return success;
}
solo.c
This is an example of a module that needs initialization
#include "nx_lib_public.h"
NXL_FUNC_RUN_CHECK_ADD(solo_init)
void solo_init(void)
{
nxl_func_run_check_hit((char *) __func__);
/* do module initialization here */
}
You can use gcc's extension __attribute__((constructor)) if gcc is ok for your project.
#include <stdio.h>
void func1() __attribute__((constructor));
void func2() __attribute__((constructor));
void func1()
{
printf("%s\n",__func__);
}
void func2()
{
printf("%s\n",__func__);
}
int main()
{
printf("main\n");
return 0;
}
//the output
func2
func1
main
I don't know how ugly the following looks but I post it anyway :-)
(The basic idea is to register function pointers, like what atexit function does.
Of course atexit implementation is different)
In the main module we can have something like this:
typedef int (*function_t)(void);
static function_t vfunctions[100]; // we can store max 100 function pointers
static int vcnt = 0; // count the registered function pointers
int add2init(function_t f)
{
// todo: error checks
vfunctions[vcnt++] = f;
return 0;
}
...
int main(void) {
...
// iterate vfunctions[] and call the functions
...
}
... and in some other module:
typedef int (*function_t)(void);
extern int add2init(function_t f);
#define M_add2init(function_name) static int int_ ## function_name = add2init(function_name)
int foo(void)
{
printf("foo\n");
return 0;
}
M_add2init(foo); // <--- register foo function
Why not write a post processing script to do the checking for you. Then run that script as part of your build process... Or better yet, make it one of your tests. You are writing tests, right? :)
For example, if each of your modules has a header file, modX.c. And if the signature of your init() function is "void init()"...
Have your script grep through all your .h files, and create a list of module names that need to be init()ed. Then have the script check that init() is indeed called on each module in main().
If your single module represents "class" entity and has instance constructor, you can use following construction:
static inline void init(void) { ... }
static int initialized = 0;
#define INIT if (__predict_false(!initialized)) { init(); initialized = 1; }
struct Foo *
foo_create(void)
{
INIT;
...
}
where "__predict_false" is your compiler's branch prediction hint. When first object is created, module is auto-initialized (for once).
Splint (and probably other Lint variants) can give a warning about functions that are defined but not called.
It's interesting that most compilers will warn you about unused variables, but not unused functions.
Larger running time is not a problem
You can conceivably implement a kind of "state-machine" for each module, wherein the actions of a function depend on the state the module is in. This state can be set to BEFORE_INIT or INITIALIZED.
For example, let's say we have module A with functions foo and bar.
The actual logic of the functions (i.e., what they actually do) would be declared like so:
void foo_logic();
void bar_logic();
Or whatever the signature is.
Then, the actual functions of the module (i.e., the actual function declared foo()) will perform a run-time check of the condition of the module, and decide what to do:
void foo() {
if (module_state == BEFORE_INIT) {
handle_not_initialized_error();
}
foo_logic();
}
This logic is repeated for all functions.
A few things to note:
This will obviously incur a huge penalty performance-wise, so is
probably not a good idea (I posted
anyway because you said runtime is
not a problem).
This is not a real state-machine, since there are only two states which are checked using a basic if, without some kind of smart general logic.
This kind of "design-pattern" works great when you're using separate threads/tasks, and the functions you're calling are actually called using some kind of IPC.
A state machine can be nicely implemented in C++, might be worth reading up on it. The same kind of idea can conceivably be coded in C with arrays of function pointers, but it's almost certainly not worth your time.
you can do something along these lines with a linker section. whenever you define an init function, place a pointer to it in a linker section just for init function pointers. then you can at least find out how many init functions have been compiled.
and if it does not matter what order the init functions are called, and the all have the same prototype, you can just call them all in a loop from main.
the exact details elude my memory, but it works soemthing like this::
in the module file...
//this is the syntax in GCC..(or would be if the underscores came through in this text editor)
initFuncPtr thisInit __attribute((section(.myinits)))__= &moduleInit;
void moduleInit(void)
{
// so init here
}
this places a pointer to the module init function in the .myinits section, but leaves the code in the .code section. so the .myinits section is nothing but pointers. you can think of this as a variable length array that module files can add to.
then you can access the section start and end address from the main. and go from there.
if the init functions all have the same protoytpe, you can just iterate over this section, calling them all.
this, in effect, is creating your own static constructor system in C.
if you are doing a large project and your linker is not at least this fully featured, you may have a problem...
Can I put up an answer to my question?
My idea was to have each function add it's name to a global list of functions, like Nick D's solution.
Then I would run through the symbol table produced by -gstab, and look for any functions named init_* that had not been called.
This is an embedded app so I have the elf image handy in flash memory.
However I don't like this idea because it means I always have to include debugging info in the binary.

Resources